//! `phrase.parse` through the C entry point the app calls, over a phone that //! has joined a synthetic file ([nothing-real-ever-goes-in-cotton-s-public-tree]). use std::ffi::{CStr, CString}; use std::sync::Arc; use serde_json::{json, Value}; use super::METHOD; use crate::ffi::open_quietly; use crate::{cotton_call, cotton_close, cotton_string_free}; /// A phone container already holding the connection record and the seeded /// replica — what a launch after a join finds. fn joined_container() -> tempfile::TempDir { let dir = tempfile::tempdir().expect("a temp container"); let layout = cotton_client::layout::Layout::new(dir.path()); std::fs::create_dir_all(layout.client_dir()).expect("the client folder"); std::fs::write( layout.connection_json(), serde_json::to_vec_pretty(&json!({ "mode": "remote", "baseUrl": "https://server.invalid", "workspaceId": crate::fixture::WORKSPACE, "ownerId": crate::fixture::OWNER, "connectedAt": "2026-10-01T10:00:00.000Z", })) .expect("json"), ) .expect("the connection record"); let replica = layout.replica(crate::fixture::WORKSPACE); std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder"); drop(crate::fixture::seeded(&replica)); dir } /// `cotton_call`s, exactly as the app makes them, against ONE opened core: C /// strings in, an owned C string out, freed by the caller. One envelope per /// `(method, request)`, in order. fn calls_through_the_abi(container: &std::path::Path, calls: &[(&str, &str)]) -> Vec { let config = CString::new( json!({ "containerPath": container.to_string_lossy(), "appVersion": "0.1.0" }).to_string(), ) .expect("no NUL"); let mut error: *mut std::ffi::c_char = std::ptr::null_mut(); let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(error.is_null() && !handle.is_null(), "the phone core opens"); let answers = calls .iter() .map(|(method, request)| { let method = CString::new(*method).expect("no NUL"); let request = CString::new(*request).expect("no NUL"); let answer = unsafe { cotton_call(handle, method.as_ptr(), request.as_ptr()) }; assert!(!answer.is_null(), "this ABI never answers a null string"); let text = unsafe { CStr::from_ptr(answer) }.to_string_lossy().to_string(); unsafe { cotton_string_free(answer) }; serde_json::from_str(&text).expect("one JSON object") }) .collect(); unsafe { cotton_close(handle) }; answers } fn request() -> Value { json!({ "text": "review Home office next Tuesday", "now": "2026-10-01T12:00:00Z", "time_zone": "Europe/Berlin", "projects": ["Cotton", "Home office"], "people": ["Sam"], }) } /// What an assistant's `parse_phrase` answers for `args`: the MCP door /// (`dispatch::call_tool` over `Ctx::new` with a token's read scope), its /// answer serialised to the text a `tools/call` carries and read back. fn through_mcp(args: &Value) -> Value { let (_dir, client) = crate::shell::client::phone_tests::attached(); let now = client.now(); let Value::Object(args) = args else { unreachable!("an object") }; client .with_writer(|file| { let scopes = vec!["read".to_string()]; let services = cotton_tools::mcp::dispatch::ToolServices::none(); let audit = |_: &str, _: &str| {}; let mut ctx = cotton_tools::mcp::dispatch::Ctx::new( file.driver, file.identity, file.owner_id, "Claude", "token-1", &scopes, now, Arc::new(cotton_tools::random::SystemRandom), Some(cotton_tools::mcp::writer::job("test")), &services, &audit, ); let answer = cotton_tools::mcp::dispatch::call_tool(&mut ctx, "parse_phrase", args) .map_err(|failure| failure.message().to_string())?; Ok(serde_json::from_str::(&answer.to_string()).expect("tools/call text")) }) .expect("the MCP door answers") } /// RULE: The app parses a phrase through cotton_call and gets exactly what an assistant's parse_phrase tool answers. #[test] fn a_phrase_parses_through_cotton_call_as_the_assistants_tool_answers() { let container = joined_container(); let envelope = calls_through_the_abi(container.path(), &[(METHOD, &request().to_string())]).remove(0); assert_eq!(envelope["ok"], json!(true), "{envelope}"); let parsed = &envelope["data"]; // Keep both readings of next Tuesday, as the phrase parser promises. assert_eq!( parsed["date"]["candidates"], json!(["2026-10-06", "2026-10-13"]) ); assert_eq!(parsed["project"]["candidates"], json!(["Home office"])); assert_eq!(parsed["project"]["text"], json!("Home office")); assert_eq!(parsed["person"], Value::Null); // ONE implementation: the app's answer is the assistant's tool's, whole. assert_eq!(*parsed, through_mcp(&request())); } #[test] fn a_request_that_is_not_an_object_and_one_missing_now_are_refused_by_name() { let container = joined_container(); let mut missing_now = request(); missing_now.as_object_mut().expect("an object").remove("now"); let answers = calls_through_the_abi( container.path(), &[(METHOD, r#"["review Home office"]"#), (METHOD, &missing_now.to_string())], ); assert_eq!(answers[0]["ok"], json!(false), "{}", answers[0]); assert_eq!(answers[0]["error"]["code"], json!("bad_request"), "{}", answers[0]); // The tool's own refusal, under the read family's code. It names the // verb and the field, which the person never reads (R6): the app is told // in plain words and the raw text goes to the log. assert_eq!(answers[1]["ok"], json!(false), "{}", answers[1]); assert_eq!(answers[1]["error"]["code"], json!("unreadable"), "{}", answers[1]); let message = answers[1]["error"]["message"].as_str().expect("a message"); assert_eq!(message, cotton_core::failure::NOT_READ, "{message}"); }