266 lines · 17.0 KB · RustRaw
//! Cotton Story on a phone that started its own database and never signed//! in: every `story.*` method answers here. Every story is invented.use serde_json::{json, Value};use super::*;use crate::handle::{CottonHandle, OpenConfig, OpenMode};use crate::methods::dispatch;/// Cotton Story's flavour as a phone opens it (the flavour folders are the/// phone lanes'; this is the manifest's shape).fn story_manifest() -> Value { json!({ "genesis": "personal", "flavour": "story", "name": "Cotton Story", "databases": "single", "database": "personal", "business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } }, "fan": { "home": false, "tools": false, "opens": "story" }, "kit": "story", "ground": "blank" })}fn phone(dir: &tempfile::TempDir) -> CottonHandle { let handle = CottonHandle::open(OpenConfig { mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(story_manifest()), }) .expect("an open core"); dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone"); handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value { dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn data(handle: &CottonHandle, table: &str, id: &str) -> Value { let got = ask(handle, "records.get", json!({ "table": table, "id": id })); if got["data"].is_object() { got["data"].clone() } else { got["record"]["data"].clone() }}fn listed(handle: &CottonHandle, table: &str, story: &str) -> Vec<Value> { let answer = ask(handle, "records.list", json!({ "table": table, "where": { "story": story }, "limit": 200 })); answer["records"].as_array().cloned().unwrap_or_default()}fn names_of(handle: &CottonHandle, table: &str, story: &str) -> Vec<String> { let mut names: Vec<String> = listed(handle, table, story).iter().map(|row| row["data"]["name"].as_str().unwrap_or_default().to_string()).collect(); names.sort(); names}/// RULE (Cotton Story contract, 17 Nov 2026): a first launch has no story and/// offers one act; a story starts with its title alone and is current; a/// scene written makes its characters and its place, keeps its heading and/// parts in step and its figures as the body changes; Return after a name/// offers the scene's other speaker first; a scene card says its number and/// length; renaming a character renames it through the scenes; a copy for/// translating is whole and linked; Fountain goes out and comes back the/// same, all signed out.#[test]fn a_story_is_written_signed_out() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone(&dir); let first = ask(&handle, "story.current", json!({})); assert_eq!((first["story"].clone(), first["stories"].as_u64()), (Value::Null, Some(0)), "a first launch: no story yet"); let story = ask(&handle, "story.start", json!({ "title": "The Last Bus" }))["story"].as_str().expect("a story").to_string(); let current = ask(&handle, "story.current", json!({})); assert_eq!((current["story"]["id"].as_str(), current["story"]["title"].as_str()), (Some(story.as_str()), Some("The Last Bus"))); let scene = ask(&handle, "story.scene.new", json!({}))["scene"].as_str().expect("a scene").to_string(); let written = ask(&handle, "story.scene.write", json!({ "id": scene, "heading": "ext. bus depot - night", "body": "Buses hum.\n\nMEERA\nYou waiting for someone?\n\nARJUN\n(holding up a ticket)\nThe bus on this ticket." })); assert_eq!(written["scene"]["setting"], "EXT."); assert_eq!(written["scene"]["time"], "night"); assert_eq!(written["made"]["places"].as_array().map(Vec::len), Some(1)); assert_eq!(written["made"]["characters"].as_array().map(Vec::len), Some(2)); assert_eq!(names_of(&handle, CHARACTER, &story), ["ARJUN", "MEERA"]); assert_eq!(names_of(&handle, PLACE, &story), ["bus depot"]); let row = data(&handle, SCENE, &scene); assert_eq!(row["speakers"], "MEERA\nARJUN"); let words = row["words"].as_f64().unwrap(); // The heading's parts move the heading. // Saving what the scene already holds (the writer's debounce) is no refusal. let again = ask(&handle, "story.scene.write", json!({ "id": scene, "body": "Buses hum.\n\nMEERA\nYou waiting for someone?\n\nARJUN\n(holding up a ticket)\nThe bus on this ticket." })); assert_eq!(again["scene"]["words"], written["scene"]["words"]); let moved = ask(&handle, "story.scene.write", json!({ "id": scene, "time": "DAWN" })); assert_eq!(moved["scene"]["heading"], "EXT. BUS DEPOT - DAWN"); // The figures follow the body. let longer = ask(&handle, "story.scene.write", json!({ "id": scene, "body": "Buses hum.\n\nMEERA\nYou waiting for someone?\n\nARJUN\n(holding up a ticket)\nThe bus on this ticket.\n\nMEERA\nThis bus left an hour ago." })); assert!(longer["scene"]["words"].as_f64().unwrap() > words); let meera = listed(&handle, CHARACTER, &story).into_iter().find(|row| row["data"]["name"] == "MEERA").unwrap(); assert_eq!((meera["data"]["lines"].as_f64(), meera["data"]["scenes"].as_f64()), (Some(2.0), Some(1.0))); // Return after a speech offers the other speaker first. let body = data(&handle, SCENE, &scene)["body"].as_str().unwrap().to_string(); let cursor = body.encode_utf16().count(); let pressed = ask(&handle, "story.press", json!({ "body": body, "cursor": cursor, "key": "return", "scene": scene })); assert_eq!(pressed["kind"], "character"); assert_eq!(pressed["names"][0], "ARJUN", "{pressed}"); // The lines of a body, with the story's names. let read = ask(&handle, "story.lines", json!({ "body": "Meera\nHi.", "story": story })); assert_eq!(read["lines"][0]["kind"], "character"); // The card and the chat. let card = ask(&handle, "story.card", json!({ "id": scene })); assert_eq!((card["number"].as_u64(), card["length"].as_str(), card["status_word"].as_str()), (Some(1), Some("under a page"), Some("Draft"))); let chat = ask(&handle, "story.chat", json!({ "id": scene })); assert_eq!(chat["two_hander"], true); // A second scene, moved before the first; near says where it stands. let second = ask(&handle, "story.scene.new", json!({ "after": scene }))["scene"].as_str().unwrap().to_string(); ask(&handle, "story.scene.write", json!({ "id": second, "heading": "INT. TEA STALL - NIGHT", "body": "DEVI\nTea?" })); ask(&handle, "story.scene.move", json!({ "id": second, "by": -1 })); let near = ask(&handle, "story.scene.near", json!({ "id": scene })); assert_eq!((near["previous"].as_str(), near["number"].as_u64(), near["of"].as_u64()), (Some(second.as_str()), Some(2), Some(2))); assert_eq!(ask(&handle, "story.write", json!({ "id": scene })), json!({ "platform_action": "open_writer", "scene": scene })); // Renaming a character renames them through the scenes. let meera_id = meera["id"].as_str().unwrap().to_string(); let renamed = ask(&handle, "story.rename", json!({ "table": CHARACTER, "id": meera_id, "name": "Mira" })); assert_eq!(renamed["scenes"], 1); let body = data(&handle, SCENE, &scene)["body"].as_str().unwrap().to_string(); assert!(body.contains("\nMIRA\nYou waiting") && !body.contains("MEERA"), "{body}"); // The script lays the story out; Fountain goes out and comes back. let script = ask(&handle, "story.script", json!({ "story": story, "region": "IN" })); assert_eq!(script["paper"]["name"], "a4"); assert_eq!(script["scenes"].as_array().map(Vec::len), Some(2)); assert_eq!(script["pages"][0]["lines"][0]["scene"]["number"], 1); let out = ask(&handle, "story.fountain.write", json!({ "story": story })); assert_eq!(out["name"], "The Last Bus.fountain"); let text = out["text"].as_str().unwrap().to_string(); let back = ask(&handle, "story.fountain.read", json!({ "text": text, "name": "The Last Bus.fountain" })); assert_eq!((back["scenes"].as_u64(), back["characters"].as_u64(), back["places"].as_u64()), (Some(2), Some(3), Some(2))); let again = ask(&handle, "story.fountain.write", json!({ "story": back["story"] })); assert_eq!(again["text"].as_str(), Some(text.as_str()), "read what you wrote, byte for byte"); assert_eq!(ask(&handle, "story.current", json!({}))["story"]["id"], back["story"], "a story brought in is current"); // A copy to translate is whole, linked and current. let copy = ask(&handle, "story.copy", json!({ "story": story, "language": "Telugu" }))["story"].as_str().unwrap().to_string(); let copied = data(&handle, STORY, ©); assert_eq!((copied["translation_of"].as_str(), copied["language"].as_str(), copied["title"].as_str()), (Some(story.as_str()), Some("Telugu"), Some("The Last Bus (Telugu)"))); assert_eq!(listed(&handle, SCENE, ©).len(), 2); assert_eq!(names_of(&handle, CHARACTER, ©), names_of(&handle, CHARACTER, &story)); // Choosing a story makes it current again. ask(&handle, "story.choose", json!({ "story": story })); assert_eq!(ask(&handle, "story.current", json!({}))["story"]["id"], json!(story));}/// RULE (contract): a Telugu scene names its speakers by the story's/// characters, never by capitals; a name chosen on the bar is forced so it/// reads as one, and becomes a character.#[test]fn a_telugu_scene_makes_its_characters() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone(&dir); let story = ask(&handle, "story.start", json!({ "title": "వర్షం" }))["story"].as_str().unwrap().to_string(); let scene = ask(&handle, "story.scene.new", json!({ "story": story }))["scene"].as_str().unwrap().to_string(); let pressed = ask(&handle, "story.press", json!({ "body": "అమ్మమ్మ", "cursor": 7, "key": "return", "kind": "character", "scene": scene })); assert_eq!((pressed["body"].as_str(), pressed["kind"].as_str()), (Some("@అమ్మమ్మ\n"), Some("dialogue"))); let body = format!("{}లోపలికి రా.", pressed["body"].as_str().unwrap()); let written = ask(&handle, "story.scene.write", json!({ "id": scene, "body": body })); assert_eq!(written["scene"]["speakers"], "అమ్మమ్మ"); assert_eq!(names_of(&handle, CHARACTER, &story), ["అమ్మమ్మ"]); // Known now, the name reads as a name without its @. let read = ask(&handle, "story.lines", json!({ "body": "అమ్మమ్మ\nరా.", "story": story })); assert_eq!((read["lines"][0]["kind"].as_str(), read["lines"][1]["kind"].as_str()), (Some("character"), Some("dialogue")));}fn deck(handle: &CottonHandle, table: &str, view: &str) -> Vec<String> { let answer = ask(handle, "shell.deck", json!({ "table": table, "view": format!("story/{view}"), "cursor": 0, "limit": 50, "timezone": "Asia/Kolkata" })); answer["cards"].as_array().expect("cards").iter().filter_map(|card| card["id"].as_str().map(str::to_string)).collect()}/// RULE (contract): Scenes, Characters, Places, Notes and Script show the/// current story only; Stories shows every story; choosing a story moves/// every other view to it.#[test]fn the_views_show_the_current_story_only() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone(&dir); let first = ask(&handle, "story.start", json!({ "title": "One" }))["story"].as_str().unwrap().to_string(); let a = ask(&handle, "story.scene.new", json!({ "story": first }))["scene"].as_str().unwrap().to_string(); ask(&handle, "story.scene.write", json!({ "id": a, "body": "MEERA\nHello." })); let second = ask(&handle, "story.start", json!({ "title": "Two" }))["story"].as_str().unwrap().to_string(); let b = ask(&handle, "story.scene.new", json!({ "story": second }))["scene"].as_str().unwrap().to_string(); ask(&handle, "story.scene.write", json!({ "id": b, "body": "ARJUN\nHi." })); assert_eq!(deck(&handle, SCENE, "scenes"), [b.clone()], "the story started last is current"); assert_eq!(deck(&handle, SCENE, "script"), [b.clone()]); assert_eq!(deck(&handle, CHARACTER, "characters").len(), 1); assert_eq!(deck(&handle, STORY, "stories").len(), 2, "Stories lists every story"); ask(&handle, "story.choose", json!({ "story": first })); assert_eq!(deck(&handle, SCENE, "scenes"), [a]); let fan = ask(&handle, "shell.fan", json!({ "timezone": "Asia/Kolkata" })); assert_eq!(fan["tiles"][0]["current"], format!("story:{first}"), "the fan stands on the story chosen");}/// Speed through the phone's own methods, rows read included (contract:/// keystroke methods in a few milliseconds, the 120-page script under a/// second, in release): `cargo test --release -p cotton-ffi --lib story_speed -- --ignored --nocapture`.#[test]#[ignore = "a measurement: run in release with --ignored --nocapture"]fn story_speed_through_the_methods() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone(&dir); let story = ask(&handle, "story.start", json!({ "title": "Long" }))["story"].as_str().unwrap().to_string(); let block = |at: usize| format!("Meera crosses the yard as bus {at} pulls out, its lights sweeping the wet concrete.\n\nMEERA\n(to herself)\nOne more shift. Just one more, and then it is somebody else's night.\n\nARJUN\nThe ticket says {at}.\n\n"); let ten: String = (0..50).map(block).collect(); let mut first = String::new(); for at in 0..60 { let scene = ask(&handle, "story.scene.new", json!({ "story": story }))["scene"].as_str().unwrap().to_string(); let body: String = (0..10).map(|n| block(at * 100 + n)).collect(); ask(&handle, "story.scene.write", json!({ "id": scene, "heading": format!("INT. DEPOT {at} - NIGHT"), "body": body })); if at == 0 { first = scene; } } // RULE: saving a body the scene already holds is no refusal (the writer saves on a debounce). ask(&handle, "story.scene.write", json!({ "id": first, "body": ten })); ask(&handle, "story.scene.write", json!({ "id": first, "body": ten })); let best = |f: &dyn Fn()| (0..10).map(|_| { let start = std::time::Instant::now(); f(); start.elapsed() }).min().unwrap(); let cursor = ten.encode_utf16().count(); let lines = best(&|| { ask(&handle, "story.lines", json!({ "body": ten, "scene": first })); }); let press = best(&|| { ask(&handle, "story.press", json!({ "body": ten, "cursor": cursor, "key": "return", "scene": first })); }); let write = best(&|| { ask(&handle, "story.scene.write", json!({ "id": first, "body": ten })); }); let script = best(&|| { ask(&handle, "story.script", json!({ "story": story })); }); let pages = ask(&handle, "story.script", json!({ "story": story }))["pages"].as_array().map(Vec::len).unwrap_or(0); println!("story.lines (10 pages, scene's names read): {lines:?}"); println!("story.press (Return): {press:?}"); println!("story.scene.write (10 pages, figures, recount over 60 scenes): {write:?}"); println!("story.script ({pages} pages): {script:?}");}/// RULE (STALE, 21 Nov 2026): a scene saved from a writer opened on an older body, while another device or the assistant changed it, is/// merged into the newer body line by line (`base`, the body the writer loaded); the answer carries the body to take and says so.#[test]fn a_scene_saved_from_an_older_body_is_merged_into_the_newer_one() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone(&dir); ask(&handle, "story.start", json!({ "title": "The Last Bus" })); let scene = ask(&handle, "story.scene.new", json!({}))["scene"].as_str().expect("a scene").to_string(); let old = "Buses hum.\n\nMEERA\nYou waiting for someone?"; ask(&handle, "story.scene.write", json!({ "id": scene, "body": old })); // Another writer adds Arjun's answer while this writer stands on `old`. let newer = format!("{old}\n\nARJUN\nThe bus on this ticket."); ask(&handle, "story.scene.write", json!({ "id": scene, "body": newer })); let saved = ask(&handle, "story.scene.write", json!({ "id": scene, "body": "Buses hum, one by one.\n\nMEERA\nYou waiting for someone?", "base": old })); let both = "Buses hum, one by one.\n\nMEERA\nYou waiting for someone?\n\nARJUN\nThe bus on this ticket."; assert_eq!(saved["scene"]["body"], json!(both), "{saved}"); assert_eq!(saved["merged"], json!(true)); assert_eq!(saved["said"], json!("This scene changed on another device while you were writing. Your changes are added to it.")); assert_eq!(data(&handle, "story_scene", &scene)["body"], json!(both)); // Unchanged from what it loaded: the newer body is the answer, nothing said. let reload = ask(&handle, "story.scene.write", json!({ "id": scene, "body": old, "base": old })); assert_eq!(reload["scene"]["body"], json!(both)); assert!(reload.get("said").is_none());}