//! Story's rings one to four under the surface, over invented stories, signed out.use serde_json::{json, Value};use tempfile::TempDir;usecrate::handle::{CottonHandle, OpenConfig, OpenMode};usecrate::methods::dispatch;fn phone(dir: &TempDir) -> CottonHandle {let manifest = 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" });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(manifest), }) .expect("an open core"); dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started"); handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value { dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn id(value: &Value) -> String { value.as_str().expect("an id").to_string()}fn records(handle: &CottonHandle, table: &str, filter: Value) -> Vec<Value> { ask(handle, "records.list", json!({ "table": table, "where": filter, "limit": 200 }))["records"].as_array().cloned().unwrap_or_default()}/// A story with one scene written whole, as an assistant writes it.fn written(handle: &CottonHandle) -> (String, String) {let story = id(&ask(handle, "story.start", json!({ "title": "The Night Bus" }))["story"]);let scene = id(&ask(handle, "story.scene.new", json!({ "story": story }))["scene"]);let body = "Rain on the shelter roof.\n\nASHA\nIs it late?\n\nRAVI\nNot yet.\n\nA bus turns the corner."; ask(handle, "story.scene.write", json!({ "id": scene, "heading": "EXT. BUS STOP - NIGHT", "body": body })); (story, scene)}fn line_ids(handle: &CottonHandle, scene: &str) -> Vec<(String, String)> { ask(handle, "story.scene", json!({ "id": scene }))["lines"].as_array().unwrap().iter().map(|line| (id(&line["id"]), line["text"].as_str().unwrap().to_string())).collect()}fn character(handle: &CottonHandle, story: &str, name: &str) -> String { records(handle, "story_character", json!({ "story": story })).iter().find(|row| row["data"]["name"] == name).map(|row| id(&row["id"])).unwrap_or_else(|| panic!("no {name}"))}/// RULE: Every line of a scene is a row with an id of its own from the first write, and a body written whole again keeps the ids of the lines it kept or edited.#[test]fn lines_keep_their_ids_when_a_body_is_written_again() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (_, scene) = written(&handle);let before = line_ids(&handle, &scene); assert_eq!(before.len(), 4); assert!(before.iter().all(|(id, _)| !id.starts_with("body:")), "rows from the first write: {before:?}");let body = "Rain on the shelter roof.\n\nASHA\nIs it very late?\n\nA dog barks.\n\nRAVI\nNot yet.\n\nA bus turns the corner."; ask(&handle, "story.scene.write", json!({ "id": scene, "body": body }));let after = line_ids(&handle, &scene);let kept: Vec<&str> = after.iter().map(|(id, _)| id.as_str()).collect(); assert_eq!(kept[0], before[0].0); assert_eq!(kept[1], before[1].0, "the edited speech keeps its id"); assert!(!before.iter().any(|(id, _)| id == kept[2]), "the new line is new"); assert_eq!(&kept[3..], [before[2].0.as_str(), before[3].0.as_str()]);}/// RULE: Renaming a character keeps every line's id and character; merging two characters gives one the other's speeches, pictures and costumes, and the other goes.#[test]fn rename_and_merge_keep_line_identity() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (story, scene) = written(&handle);let before = line_ids(&handle, &scene);let ravi = character(&handle, &story, "RAVI"); ask(&handle, "story.rename", json!({ "table": "story_character", "id": ravi, "name": "Ravi Kumar" })); assert_eq!(line_ids(&handle, &scene).iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(), before.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>());let asha = character(&handle, &story, "ASHA"); ask(&handle, "records.create", json!({ "table": "story_costume", "data": { "story": story, "character": asha, "name": "Yellow raincoat", "day": 1 } })); ask(&handle, "story.picture.add", json!({ "character": asha, "picture": "invented/photos/asha.jpg" })); ask(&handle, "story.merge", json!({ "table": "story_character", "id": asha, "into": ravi }));let person = ask(&handle, "story.person", json!({ "id": ravi })); assert_eq!(person["lines"], 2); assert_eq!(person["costumes"].as_array().unwrap().len(), 1); assert_eq!(person["pictures"].as_array().unwrap().len(), 1); assert_eq!(person["scene_ids"], json!([scene])); assert!(records(&handle, "story_character", json!({ "story": story })).iter().all(|row| row["id"] != asha)); assert_eq!(line_ids(&handle, &scene)[1].0, before[1].0, "Asha's line, now Ravi's, keeps its id");}/// RULE: A scene split at a line makes the next scene with the lines from there on, ids kept; merged back, the lines return with the same ids.#[test]fn a_scene_splits_and_merges_with_its_lines_ids() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (_, scene) = written(&handle);let before = line_ids(&handle, &scene);let split = ask(&handle, "story.scene.split", json!({ "id": scene, "at": before[2].0 }));let second = id(&split["scene"]); assert_eq!(line_ids(&handle, &scene).iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(), [before[0].0.clone(), before[1].0.clone()]); assert_eq!(line_ids(&handle, &second).iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(), [before[2].0.clone(), before[3].0.clone()]);let near = ask(&handle, "story.scene.near", json!({ "id": second })); assert_eq!((near["number"].as_u64(), near["previous"].as_str()), (Some(2), Some(scene.as_str()))); ask(&handle, "story.scene.merge", json!({ "id": second, "into": scene })); assert_eq!(line_ids(&handle, &scene), before);}/// RULE: Places come from headings, are offered most used first and named as names (a heading's "BUS STOP" reads "Bus Stop", as the home says it), merge into one with their scenes and pictures, and a place page carries its pictures.#[test]fn places_are_offered_merged_and_pictured() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (story, scene) = written(&handle);let other = id(&ask(&handle, "story.scene.new", json!({ "story": story }))["scene"]); ask(&handle, "story.scene.write", json!({ "id": other, "setting": "EXT.", "place": "Bus shelter", "time": "NIGHT", "day": 2 }));let places = ask(&handle, "story.places", json!({ "story": story }))["places"].as_array().unwrap().clone(); assert_eq!(places.len(), 2);let stop = places.iter().find(|place| place["name"] == "Bus Stop").map(|place| id(&place["id"])).unwrap();let shelter = places.iter().find(|place| place["name"] == "Bus shelter").map(|place| id(&place["id"])).unwrap(); ask(&handle, "story.picture.add", json!({ "place": shelter, "picture": "invented/photos/shelter.jpg", "caption": "Tin roof" })); ask(&handle, "story.merge", json!({ "table": "story_place", "id": shelter, "into": stop }));let page = ask(&handle, "story.place", json!({ "id": stop })); assert_eq!(page["scenes"], 2); assert_eq!(page["pictures"][0]["caption"], "Tin roof");let heading = records(&handle, "story_scene", json!({ "story": story })).iter().find(|row| row["id"] == other.as_str()).map(|row| row["data"].clone()).unwrap(); assert_eq!((heading["heading"].as_str(), heading["day"].as_f64()), (Some("EXT. BUS STOP - NIGHT"), Some(2.0)));let _ = scene;}/// RULE: Pictures at three levels list in order, move, and go to Deleted; a costume and a thing tie to scenes by identity.#[test]fn pictures_things_and_costumes() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (story, scene) = written(&handle);let asha = character(&handle, &story, "ASHA");let first = id(&ask(&handle, "story.picture.add", json!({ "character": asha, "picture": "invented/photos/a.jpg" }))["picture"]["id"]);let second = id(&ask(&handle, "story.picture.add", json!({ "character": asha, "picture": "invented/photos/b.jpg" }))["picture"]["id"]); ask(&handle, "story.picture.add", json!({ "character": asha, "day": 3, "picture": "invented/photos/c.jpg" })); ask(&handle, "story.picture.add", json!({ "scene": scene, "picture": "invented/photos/d.jpg" }));let moved = ask(&handle, "story.picture.move", json!({ "id": second, "after": "start" })); assert_eq!(moved["pictures"].as_array().unwrap().iter().map(|one| id(&one["id"])).collect::<Vec<_>>(), [second.clone(), first.clone()]); assert_eq!(ask(&handle, "story.pictures", json!({ "character": asha, "day": 3 }))["pictures"].as_array().unwrap().len(), 1); assert_eq!(ask(&handle, "story.pictures", json!({ "scene": scene }))["pictures"].as_array().unwrap().len(), 1); ask(&handle, "story.picture.remove", json!({ "id": first })); assert!(ask(&handle, "story.pictures", json!({ "character": asha }))["pictures"].as_array().unwrap().iter().all(|one| one["id"] != first.as_str()));let umbrella = id(&ask(&handle, "records.create", json!({ "table": "story_thing", "data": { "story": story, "name": "Black umbrella", "kind": "prop" } }))["record"]["id"]);let coat = id(&ask(&handle, "records.create", json!({ "table": "story_costume", "data": { "story": story, "character": asha, "name": "Raincoat", "day": 1 } }))["record"]["id"]); ask(&handle, "records.create", json!({ "table": "story_use", "data": { "story": story, "scene": scene, "thing": umbrella, "character": asha } })); ask(&handle, "records.create", json!({ "table": "story_use", "data": { "story": story, "scene": scene, "costume": coat } })); assert_eq!(ask(&handle, "story.things", json!({ "story": story }))["things"][0]["scene_ids"], json!([scene])); assert_eq!(ask(&handle, "story.costumes", json!({ "character": asha }))["costumes"][0]["scene_ids"], json!([scene]));}/// RULE: A draft is frozen: what changed since is told by identity, and going back brings the draft's scenes, order and lines with their ids, the scene made since to Deleted.#[test]fn a_draft_is_marked_compared_and_gone_back_to() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (story, scene) = written(&handle);let before = line_ids(&handle, &scene);// RULE (the Android walk, 25 Nov 2026): the name field suggests the next draft's name, the first one "First draft". assert_eq!(ask(&handle, "story.drafts.list", json!({ "story": story }))["hint"], "First draft");let draft = id(&ask(&handle, "story.drafts.mark", json!({ "story": story, "name": "First draft" }))["draft"]); assert_eq!(ask(&handle, "story.drafts.list", json!({ "story": story }))["hint"], "Second draft");let body = "Rain on the shelter roof.\n\nASHA\nIs it very late?\n\nA bus turns the corner."; ask(&handle, "story.scene.write", json!({ "id": scene, "body": body }));let added = id(&ask(&handle, "story.scene.new", json!({ "story": story }))["scene"]); ask(&handle, "story.scene.write", json!({ "id": added, "heading": "INT. BUS - NIGHT", "body": "Empty seats." }));let since = ask(&handle, "story.drafts.changes", json!({ "draft": draft })); assert_eq!(since["since"]["scenes_added"], 1); assert_eq!(since["since"]["scenes_changed"], 1); assert_eq!((since["since"]["lines_changed"].as_u64(), since["since"]["lines_removed"].as_u64()), (Some(1), Some(1)));let read = ask(&handle, "story.drafts.read", json!({ "draft": draft })); assert!(read["fountain_text"].as_str().unwrap().contains("Not yet.")); assert_eq!(ask(&handle, "story.drafts.list", json!({ "story": story }))["drafts"][0]["name"], "First draft"); ask(&handle, "story.drafts.restore", json!({ "draft": draft })); assert_eq!(line_ids(&handle, &scene), before, "every line back, with its id"); assert!(records(&handle, "story_scene", json!({ "story": story })).iter().all(|row| row["id"] != added.as_str()));let again = ask(&handle, "story.drafts.changes", json!({ "draft": draft })); assert!(again["scenes"].as_array().unwrap().iter().all(|one| one["change"] == "same"), "{again}");}/// RULE: A story in any script keeps its words as written: a Telugu speaker is a speaker, nothing is upper-cased that has no case, and Final Draft carries it as written.#[test]fn any_script_in_any_line() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let story = id(&ask(&handle, "story.start", json!({ "title": "రాత్రి బస్సు" }))["story"]);let scene = id(&ask(&handle, "story.scene.new", json!({ "story": story }))["scene"]); ask(&handle, "story.character.add", json!({ "story": story, "name": "రవి" })); ask(&handle, "story.scene.write", json!({ "id": scene, "setting": "EXT.", "place": "బస్ స్టాప్", "time": "రాత్రి", "body": "వర్షం.\n\n@రవి\nఇంకా లేదు.\n\nASHA\nکیا دیر ہو گئی؟\n\nハナが来る。" }));let lines = ask(&handle, "story.scene", json!({ "id": scene }))["lines"].as_array().unwrap().clone(); assert_eq!(lines.iter().map(|line| line["kind"].as_str().unwrap()).collect::<Vec<_>>(), ["action", "dialogue", "dialogue", "action"]); assert_eq!(lines[1]["text"], "ఇంకా లేదు."); assert_eq!(lines[2]["text"], "کیا دیر ہو گئی؟");let heading = records(&handle, "story_scene", json!({ "story": story }))[0]["data"]["heading"].clone(); assert_eq!(heading, "EXT. బస్ స్టాప్ - రాత్రి");let fdx = ask(&handle, "story.fdx.write", json!({ "story": story })); assert!(fdx["text"].as_str().unwrap().contains("<Text>రవి</Text>")); assert_eq!(fdx["name"], "రాత్రి బస్సు.fdx");}/// RULE: A script file brought in becomes a new story by what it is: a Final Draft file by its root (a Telugu speaker kept as written), a printed PDF by where its lines stand (with a line asking the person to read it through), else Fountain; a PDF with no words is refused by name.#[test]fn a_script_file_comes_in_by_what_it_is() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let story = id(&ask(&handle, "story.start", json!({ "title": "రాత్రి బస్సు" }))["story"]);let scene = id(&ask(&handle, "story.scene.new", json!({ "story": story }))["scene"]); ask(&handle, "story.character.add", json!({ "story": story, "name": "రవి" })); ask(&handle, "story.scene.write", json!({ "id": scene, "setting": "EXT.", "place": "బస్ స్టాప్", "time": "రాత్రి", "body": "వర్షం.\n\n@రవి\nఇంకా లేదు.\n\nरीना\nचलो।" }));let fdx = ask(&handle, "story.fdx.write", json!({ "story": story }));let file = dir.path().join("in.fdx"); std::fs::write(&file, fdx["text"].as_str().unwrap()).unwrap();let made = ask(&handle, "story.bring_in", json!({ "path": file.to_string_lossy(), "name": "రాత్రి బస్సు.fdx" })); assert_eq!(made["from"], "fdx"); assert_eq!(made["scenes"], 1); assert!(made.get("check").is_none());let scenes = records(&handle, "story_scene", json!({ "story": made["story"] })); assert_eq!(scenes[0]["data"]["heading"], "EXT. బస్ స్టాప్ - రాత్రి"); assert!(scenes[0]["data"]["body"].as_str().unwrap().contains("@రవి\nఇంకా లేదు."), "{}", scenes[0]["data"]["body"]);// A printed page: a heading and action at the margin, a name, an aside and speech in their columns.use cotton_core::health::lab::sample_pdf::{pdf, Text};let at = |chars: f32, row: f32, words: &str| Text { x: 108.0 + chars * 7.2, y: 72.0 + row * 12.0, size: 12.0, text: words.to_string() };let page = vec![Text { x: 80.0, y: 72.0, size: 12.0, text: "1".into() }, at(0.0, 0.0, "INT. TEA STALL - MORNING"), at(0.0, 2.0, "Steam off the kettle."), at(22.0, 4.0, "MEERA"), at(16.0, 5.0, "(not looking up)"), at(10.0, 6.0, "You took money from him?"), at(53.0, 8.0, "CUT TO:"), at(0.0, 10.0, "EXT. JETTY - NIGHT"), at(0.0, 12.0, "The boat is gone."), ];let file = dir.path().join("in.pdf"); std::fs::write(&file, pdf(&[page])).unwrap();let made = ask(&handle, "story.bring_in", json!({ "path": file.to_string_lossy() })); assert_eq!(made["from"], "pdf"); assert_eq!(made["scenes"], 2); assert!(made["check"].as_str().is_some_and(|line| !line.is_empty()));let scenes = records(&handle, "story_scene", json!({ "story": made["story"] }));let tea = scenes.iter().find(|row| row["data"]["heading"] == "INT. TEA STALL - MORNING").expect("the tea stall"); assert_eq!(tea["data"]["body"], "Steam off the kettle.\n\nMEERA\n(not looking up)\nYou took money from him?\n\n>CUT TO:"); std::fs::write(&file, pdf(&[Vec::new()])).unwrap();let refused = dispatch(&handle, "story.bring_in", &json!({ "path": file.to_string_lossy() })).expect_err("no words"); assert_eq!(refused.code, "no_text");}/// RULE: A person's or a place's face is always its first picture of itself: moving another to the start makes it the face, removing the face hands it on, and a picture of a story day never becomes the face.#[test]fn the_first_picture_is_the_face() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (story, _) = written(&handle);let asha = character(&handle, &story, "ASHA");let face = |handle: &CottonHandle| ask(handle, "story.person", json!({ "id": asha }))["picture"].clone(); ask(&handle, "story.picture.add", json!({ "character": asha, "day": 2, "picture": "invented/photos/asha-day2.jpg" })); assert_eq!(face(&handle), Value::Null);let first = id(&ask(&handle, "story.picture.add", json!({ "character": asha, "picture": "invented/photos/asha.jpg" }))["picture"]["id"]);let second = id(&ask(&handle, "story.picture.add", json!({ "character": asha, "picture": "invented/photos/asha-2.jpg" }))["picture"]["id"]); assert_eq!(face(&handle), "invented/photos/asha.jpg"); ask(&handle, "story.picture.move", json!({ "id": second, "after": "start" })); assert_eq!(face(&handle), "invented/photos/asha-2.jpg"); ask(&handle, "story.picture.remove", json!({ "id": second })); assert_eq!(face(&handle), "invented/photos/asha.jpg"); ask(&handle, "story.picture.remove", json!({ "id": first })); assert_eq!(face(&handle), Value::Null);}/// RULE: The Places list and a place's page say what the script says about a place (inside or outside, how many scenes, its times of day, how many pictures, minutes of the film, who speaks in each scene), and a character's page says their lines in each scene and the story days they are in.#[test]fn places_and_people_say_what_the_script_knows() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let (story, scene) = written(&handle); ask(&handle, "story.scene.write", json!({ "id": scene, "day": 3 }));let places = ask(&handle, "story.places", json!({ "story": story }))["places"].as_array().unwrap().clone(); assert_eq!(places[0]["line"], "Outside · 1 scene · Night · no pictures yet");let page = ask(&handle, "story.place", json!({ "id": places[0]["id"] })); assert!(page["line"].as_str().unwrap().starts_with("Outside · 1 scene"), "{page}"); assert_eq!(page["times"], json!([{ "time": "Night", "scenes": 1 }])); assert_eq!(page["people"][&scene], "Asha, Ravi");let asha = character(&handle, &story, "ASHA");let person = ask(&handle, "story.person", json!({ "id": asha })); assert_eq!(person["lines_in"][&scene], "1 line"); assert_eq!(person["days"], json!([{ "day": 3, "label": "Day 3" }]));}/// RULE: A phone that stands on its own, with no story, is not waiting for scripts: its home is the empty screen, never "Loading your data…".#[test]fn a_phone_on_its_own_is_not_waiting_for_scripts() {let dir = TempDir::new().unwrap();let handle = phone(&dir); assert_eq!(ask(&handle, "story.list", json!({}))["arriving"], false); assert_eq!(ask(&handle, "story.current", json!({}))["arriving"], false);}/// RULE: One script file comes in at a time: a second Bring in while one is still being read is refused `busy` with the words the phone shows while it waits ("Bringing in…"), and makes no second story; once the first answers, the next is read.#[test]fn a_second_bring_in_waits_for_the_first() {let dir = TempDir::new().unwrap();let handle = phone(&dir);let file = dir.path().join("in.fountain"); std::fs::write(&file, "Title: Night Bus\n\nEXT. BUS STOP - NIGHT\n\nRain.\n").unwrap();let held = crate::phone::story::BringingIn::hold(&handle).expect("nothing under way");let refused = dispatch(&handle, "story.bring_in", &json!({ "path": file.to_string_lossy() })).expect_err("one is under way"); assert_eq!(refused.code, "busy"); assert_eq!(refused.message, "Importing your script…");let none = ask(&handle, "story.list", json!({})); assert!(none["stories"].as_array().expect("the list").is_empty(), "no second story: {none}"); drop(held);let made = ask(&handle, "story.bring_in", json!({ "path": file.to_string_lossy() })); assert_eq!(made["scenes"], 1); assert!(crate::phone::story::BringingIn::hold(&handle).is_some(), "a refusal or an answer lets go");}