//! Every message this protocol speaks, pinned to a file a person can read.//!//! `PROTOCOL.md` is the prose and these two files are the contract: a rename,//! a retagged variant or a field that quietly became optional fails HERE,//! before it becomes a client on another machine that stops understanding a//! session.//!//! The vectors are held in BOTH directions. Parsing them proves the host reads//! what a client writes; re-encoding what was parsed and comparing the JSON//! proves the host writes what a client reads. Comparing the parsed JSON//! rather than the literal text is deliberate: key order and float spelling//! are serde's, and pinning those would make the file a snapshot of an//! implementation instead of a statement of a protocol.use cotton_session_host::protocol::{parse, Event, Request};const REQUESTS: &str = include_str!("fixtures/protocol-vectors.jsonl");const EVENTS: &str = include_str!("fixtures/protocol-events.jsonl");fn lines(text: &str) -> Vec<&str> { text.lines().filter(|line| !line.trim().is_empty()).collect()}/// What the line says, with the fields serde leaves out when they are absent/// removed from BOTH sides — an optional field written as `null` and one left/// out are the same message.fn without_nulls(value: &serde_json::Value) -> serde_json::Value {match value { serde_json::Value::Object(fields) => serde_json::Value::Object( fields .iter() .filter(|(_, held)| !held.is_null()) .map(|(name, held)| (name.clone(), without_nulls(held))) .collect(), ), serde_json::Value::Array(items) => { serde_json::Value::Array(items.iter().map(without_nulls).collect()) } other => other.clone(), }}#[test]fn every_request_vector_parses_and_re_encodes_to_the_same_message() {let vectors = lines(REQUESTS); assert!( vectors.len() >= 16,"the vectors cover the whole client half — found {}", vectors.len() );for line in vectors {let parsed: Request = parse(line).unwrap_or_else(|error| { panic!("this vector is not a request this host speaks: {line}\n {error}") });let back = serde_json::to_value(&parsed).expect("it re-encodes");let original: serde_json::Value = serde_json::from_str(line).expect("the vector is JSON"); assert_eq!( without_nulls(&back), without_nulls(&original),"re-encoding changed this message: {line}" ); }}#[test]fn every_event_vector_parses_and_re_encodes_to_the_same_message() {let vectors = lines(EVENTS); assert!( vectors.len() >= 15,"the vectors cover the whole daemon half — found {}", vectors.len() );for line in vectors {let parsed: Event = parse(line).unwrap_or_else(|error| { panic!("this vector is not an event this host speaks: {line}\n {error}") });let back = serde_json::to_value(&parsed).expect("it re-encodes");let original: serde_json::Value = serde_json::from_str(line).expect("the vector is JSON"); assert_eq!( without_nulls(&back), without_nulls(&original),"re-encoding changed this message: {line}" ); }}#[test]fn the_vectors_cover_every_verb_and_every_event_kind() {let tags = |text: &str| { lines(text) .iter() .filter_map(|line| { serde_json::from_str::<serde_json::Value>(line) .ok()? .get("t")? .as_str() .map(str::to_string) }) .collect::<std::collections::BTreeSet<_>>() };let requests = tags(REQUESTS);for verb in ["spawn","attach","write","resize","detach","stop","decide","list","subscribe","sample","restart","hook","statusline", ] { assert!(requests.contains(verb), "no vector covers `{verb}`"); }let events = tags(EVENTS);for kind in ["spawned","attached","data","sessions","state","turn","spoke","tasks","usage","sample","restarting","exited","decision","ok","error", ] { assert!(events.contains(kind), "no vector covers the `{kind}` event"); }}#[test]fn a_spawn_without_a_session_id_is_a_spawn_the_host_mints_one_for() {let without = lines(REQUESTS) .iter() .find(|line| line.contains("\"t\":\"spawn\"") && !line.contains("session_id")) .copied() .expect("a vector covers a spawn with no session id");letRequest::Spawn { session_id, .. } = parse::<Request>(without).expect("it parses") else { panic!("that vector is a spawn"); }; assert_eq!(session_id, None);}#[test]fn an_optional_field_left_out_never_becomes_a_null_on_the_way_back() {let attach = lines(REQUESTS) .iter() .find(|line| line.contains("\"t\":\"attach\"") && !line.contains("from_offset")) .copied() .expect("a vector covers an attach with no offset");let parsed: Request = parse(attach).expect("it parses");let back = serde_json::to_string(&parsed).expect("it re-encodes"); assert!( !back.contains("from_offset"),"an absent offset stays absent — got {back}" );}#[test]fn a_sample_carries_which_binary_the_helper_runs_and_whether_it_is_waiting_to_restart() {// The 2026-09-22 failure: a helper three days out of date reported a// version that could not say so. Both fields are pinned here so a rename// is a red test rather than a Mac whose staleness nothing can see.let pending = lines(EVENTS) .iter() .find(|line| line.contains("\"update_pending\":true")) .copied() .expect("a vector covers a helper waiting to restart");letEvent::Sample { sample } = parse::<Event>(pending).expect("it parses") else { panic!("that vector is a sample"); }; assert!(sample.update_pending); assert!(!sample.binary_fingerprint.is_empty());}#[test]fn a_sample_from_a_helper_that_predates_a_field_still_parses() {// The helper OUTLIVES the app, so a freshly started app reads samples from// whatever was already running — including one built before these fields// existed. An absent field is the default, never a refused line.let old = r#"{"t":"sample","sampled_at":"2026-09-18T09:00:00Z","load1":0.5,"mem_free_pct":50,"mem_total_gb":16.0,"disk_free_gb":100.0,"cpu_count":10,"sessions_running":0,"build_lock_held":false,"agents":{},"host_version":"0.1.0"}"#;letEvent::Sample { sample } = parse::<Event>(old).expect("it parses") else { panic!("it is a sample"); }; assert_eq!(sample.binary_fingerprint, ""); assert!(!sample.update_pending);// And the measurement, added the same way: an unmeasured Mac is zero// committed with no peak, which is what a helper that cannot measure and a// helper too old to know how both look like. assert_eq!(sample.mem_committed_gb, 0.0); assert_eq!(sample.session_peak_gb, None); assert_eq!(sample.session_peak_samples, 0);// And what the machine IS: a helper too old to say has not said — `None`,// never a blank chip or a zero-byte drive — and a sample carrying none// re-encodes without the keys, so the old line round-trips as itself. assert_eq!(sample.chip, None); assert_eq!(sample.os_version, None); assert_eq!(sample.disk_total_gb, None);let again = serde_json::to_string(&Event::Sample { sample }).expect("encodes"); assert!(!again.contains("chip"), "an unsaid fact is left out on the way out — {again}"); assert!(!again.contains("disk_total_gb"), "{again}");}#[test]fn a_sample_says_what_this_mac_has_promised_and_how_many_readings_say_so() {// WHAT ADMITS WORK. The build lock is still on the line and still true;// what a dispatcher subtracts is the committed number, and it can only// weigh the peak because the sample count is beside it.let measured = lines(EVENTS) .iter() .find(|line| line.contains("\"session_peak_gb\"")) .copied() .expect("a vector covers a Mac with a measured session");letEvent::Sample { sample } = parse::<Event>(measured).expect("it parses") else { panic!("that vector is a sample"); }; assert!(sample.mem_committed_gb > 0.0); assert!(sample.session_peak_gb.is_some_and(|peak| peak > 0.0)); assert!( sample.session_peak_samples > 0,"a peak with no readings behind it is not a budget" );}#[test]fn a_restart_is_answered_by_one_of_two_restarting_events() {let answers: Vec<Event> = lines(EVENTS) .iter() .filter(|line| line.contains("\"t\":\"restarting\"")) .map(|line| parse::<Event>(line).expect("it parses")) .collect(); assert_eq!(answers.len(), 2, "one going, one deferring"); assert!(answers.contains(&Event::Restarting { restarting: true, sessions_running: 0 })); assert!(answers.contains(&Event::Restarting { restarting: false, sessions_running: 2 }));}