usesuper::*;use serde_json::json;/// RULE: A device's reported state never carries a value from a secret row or a URL with a token: only the known fields are kept, and every sentence loses credentials, Bearer values and URL queries before it is sent or written.#[test]fn a_placement_value_and_a_token_never_reach_the_stored_state() {let placement_value = "invented-placement-value-7f3a";let arrived = json!({"build": "254","schema": 135,"last_answer": "400 schemaVersion must be 132","placement": placement_value,"secrets": [{"name": "INVENTED", "value": placement_value}],"open_problem": "Could not open https://relay.example/v1/sync?token=abc123 — Authorization: Bearer abc123","copy": "copying · 400 MB to go · key=abc123", });let state = ReportedState::accept(&arrived).expect("known fields arrived");let stored = serde_json::to_string(&state.to_value()).unwrap(); assert!(!stored.contains(placement_value), "{stored}"); assert!(!stored.contains("abc123"), "{stored}"); assert!(stored.contains("Bearer ‹redacted›"), "{stored}"); assert_eq!(state.build.as_deref(), Some("254")); assert_eq!(state.last_answer.as_deref(), Some("400 schemaVersion must be 132"));}#[test]fn a_bearer_line_in_a_log_reads_redacted() { assert_eq!(clean_text("GET /v1/me Bearer x"), "GET /v1/me Bearer ‹redacted›");}#[test]fn nothing_known_is_no_state() { assert_eq!(ReportedState::accept(&json!({"placement": "x"})), None); assert_eq!(ReportedState::accept(&json!("a string")), None);}/// RULE: A Mac writes a device's reported state only when something but the time changed, or the stored time is ten minutes old, because every write is a synced change every device pulls.#[test]fn only_a_change_or_a_stale_time_is_written() {let at = |minute: u32| ReportedState { last_exchange_at: Some(format!("2026-10-12T10:{minute:02}:00Z")), last_answer: Some("ok".into()), unsent: Some(0), ..ReportedState::default() };let now = |minute: i64| chrono::DateTime::parse_from_rfc3339("2026-10-12T10:00:00Z").unwrap().timestamp_millis() + minute * 60_000; assert!(at(1).worth_writing(None, now(1))); assert!(!at(1).worth_writing(Some(&at(0)), now(1)), "only the time moved"); assert!(at(10).worth_writing(Some(&at(0)), now(10)), "ten minutes on, the time is said again");let changed = ReportedState { unsent: Some(3), ..at(1) }; assert!(changed.worth_writing(Some(&at(0)), now(1)));}/// RULE: Reported state preserves every file's actual stamp and redacts its refusal independently; the serving Mac must distinguish a lagging copy from the build schema without retaining credential-shaped diagnostics.#[test]fn each_database_stamp_survives_the_state_whitelist() {let state = ReportedState::accept(&serde_json::json!({"schema": 135,"bundleId": "com.example.synthetic","databases": [ {"databaseId": "old", "filename": "old/replica.db", "schemaVersion": 93}, {"databaseId": "bad", "filename": "bad/replica.db", "schemaVersion": null,"problem": "no such table: synthetic_table Bearer synthetic-secret"} ] })).unwrap().to_value(); assert_eq!(state["schema"], 135); assert_eq!(state["databases"][1]["schemaVersion"], 93); assert!(state["databases"][0]["schemaVersion"].is_null()); assert!(state["databases"][0]["problem"].as_str().unwrap().contains("synthetic_table")); assert!(!state.to_string().contains("synthetic-secret")); assert_eq!(state["bundleId"], "com.example.synthetic");}/// RULE: A phone's MetricKit payload reaches its device row: a usage with a hitch rate makes the state worth writing and the row's columns read it as numbers (8 ms/s of hitching is 99.2 % smooth scrolling); a usage with no readable window or an impossible ratio is dropped, never written (fanperf, owner 15 Oct 2026: "prove it, keep it proven").#[test]fn a_payload_with_a_hitch_rate_writes_the_row_and_reads_as_numbers() {let before = ReportedState { build: Some("synthetic-build".into()), ..Default::default() };let arrived = json!({"build": "synthetic-build","usage": {"until": "2026-10-15T00:00:00Z", "hitch_us_per_s": 8000, "hangs": 0, "cpu_ms": 41_400, "peak_memory_bytes": 212_000_000_u64, "payload": "dropped"}, });let after = ReportedState::accept(&arrived).expect("a known state"); assert!(after.worth_writing(Some(&before), 0), "a new payload is a change the Mac writes");let stored = after.to_value(); assert!(stored["usage"].get("payload").is_none(), "only the four figures are kept");let columns = crate::device::words::usage_columns(Some(&stored)); assert_eq!(columns["smooth_scrolling"], json!(99.2)); assert_eq!(columns["hangs_today"], json!(0)); assert_eq!(columns["cpu_time_today"], json!(41)); assert_eq!(columns["peak_memory"], json!(212_000_000_u64));for usage in [ json!({"until": "yesterday", "hangs": 1}), json!({"until": "2026-10-15T00:00:00Z", "hitch_us_per_s": 1_000_001}), json!({"until": "2026-10-15T00:00:00Z"}), ] {let state = ReportedState::accept(&json!({"build": "synthetic-build", "usage": usage})).expect("the build stays"); assert!(state.usage.is_none(), "{usage} is not written"); } assert!(crate::device::words::usage_columns(None)["smooth_scrolling"].is_null());}/// RULE: A device's state carries, per database, the bytes its replica, its write-ahead log, its retained copies, its media and its thumbnails hold on disk — kept through the whitelist so the serving Mac can say what a phone holds — and a size that moved is said with the next change or restate, never written on its own (row 8, 22 Oct 2026).#[test]fn each_databases_disk_holding_survives_the_whitelist_and_rides_along() {let arrived = json!({"last_exchange_at": "2026-10-22T10:00:00Z","databases": [{"databaseId": "synthetic", "filename": "synthetic/replica.db", "schemaVersion": 141,"disk": {"replicaBytes": 4096, "walBytes": 0, "retainedCopyBytes": 8192, "mediaBytes": 1000, "thumbnailBytes": 200, "unknown": 1} }] });let state = ReportedState::accept(&arrived).expect("a known state");let disk = state.databases[0].disk.clone().expect("the holding is kept"); assert_eq!( disk,crate::device::reported_state::DiskHolding { replica_bytes: 4096, wal_bytes: 0, retained_copy_bytes: 8192, media_bytes: Some(1000), thumbnail_bytes: Some(200), } ); assert_eq!(state.to_value()["databases"][0]["disk"]["retainedCopyBytes"], 8192); assert!(state.to_value()["databases"][0]["disk"].get("unknown").is_none());let grown = {letmut grown = state.clone(); grown.last_exchange_at = Some("2026-10-22T10:01:00Z".into()); grown.databases[0].disk.as_mut().expect("disk").wal_bytes = 1_048_576; grown };let now = |minute: i64| chrono::DateTime::parse_from_rfc3339("2026-10-22T10:00:00Z").unwrap().timestamp_millis() + minute * 60_000; assert!(!grown.worth_writing(Some(&state), now(1)), "a size alone is not a write");let restated = ReportedState { last_exchange_at: Some("2026-10-22T10:10:00Z".into()), ..grown.clone() }; assert!(restated.worth_writing(Some(&state), now(10)), "the restate carries it");let changed = ReportedState { unsent: Some(2), ..grown }; assert!(changed.worth_writing(Some(&state), now(1)), "a change carries it");}/// RULE (SITES 5): the phone's Sites figures ride in the reported state as said, camelCase, and a state with only/// them is still a state worth keeping; a stored state without them reads as none.#[test]fn the_sites_figures_ride_in_the_reported_state() {let said = serde_json::json!({ "sites": { "alive": 3, "mostAlive": 4, "limit": 4, "letGo": 2, "warnings": 1, "webEnded": 1, "peakFootprintMb": 412, "leastHeadroomMb": 950 } });let state = ReportedState::accept(&said).expect("figures alone are a state");let sites = state.sites.clone().unwrap(); assert_eq!((sites.alive, sites.most_alive, sites.limit, sites.let_go, sites.warnings, sites.web_ended), (3, 4, 4, 2, 1, 1)); assert_eq!((sites.peak_footprint_mb, sites.least_headroom_mb), (Some(412), Some(950))); assert_eq!(state.to_value()["sites"]["peakFootprintMb"], 412); assert_eq!(ReportedState::accept(&serde_json::json!({ "build": "synthetic-build" })).unwrap().sites, None);}/// RULE (LOOK-ONLY, 27 Nov 2026): Albums' first-look counts ride in the reported state as said, camelCase, counts and/// timings only; a state with only them is still a state worth keeping.#[test]fn the_albums_first_look_counts_ride_in_the_reported_state() {let said = serde_json::json!({ "albums": { "photos": 60000, "videos": 4000, "looked": 1912, "small": 30, "noLocalPicture": 800,"owed": 830, "failed": 2, "seconds": 600, "perMinute": 700, "faces": 900, "vectors": 610, "shownGroups": 12, "peakFootprintMb": 410, "warnings": 0 } });let state = ReportedState::accept(&said).expect("counts alone are a state");let albums = state.albums.clone().unwrap(); assert_eq!((albums.photos, albums.looked, albums.small, albums.no_local_picture, albums.owed, albums.failed), (60000, 1912, 30, 800, 830, 2)); assert_eq!((albums.seconds, albums.per_minute, albums.shown_groups, albums.peak_footprint_mb), (600, Some(700), 12, Some(410))); assert_eq!(state.to_value()["albums"]["noLocalPicture"], 800); assert_eq!(ReportedState::accept(&serde_json::json!({ "build": "synthetic-build" })).unwrap().albums, None);}/// RULE (UNSENT SEEN, 26 Nov 2026): what waits is sent as table names and refusal codes with counts only; a key no table or code can be is dropped, at most NAMED_COUNTS_KEPT are sent, and empty maps are not sent at all.#[test]fn waiting_counts_are_names_and_counts_only() {let state = ReportedState { waiting_by_table: [("cotton_notes".to_string(), 2), ("A value, not a name".to_string(), 9)].into_iter().collect(), waiting_by_code: (0..60).map(|n| (format!("code_{n:02}"), 1)).collect(), ..ReportedState::default() } .cleaned(); assert_eq!(state.waiting_by_table.into_iter().collect::<Vec<_>>(), vec![("cotton_notes".to_string(), 2)]); assert_eq!(state.waiting_by_code.len(), super::NAMED_COUNTS_KEPT);let empty = ReportedState::default().cleaned().to_value(); assert!(empty.get("waiting_by_table").is_none() && empty.get("waiting_by_code").is_none(), "{empty}");}