//! Every number the dispatcher reads, and the text it was read out of.usesuper::*;usecrate::clock::FixedClock;#[test]fn a_version_is_read_out_of_whatever_the_agent_printed() { assert_eq!(parse_version("2.1.274 (Claude Code)").as_deref(), Some("2.1.274")); assert_eq!(parse_version("codex-cli 0.55.0").as_deref(), Some("0.55.0")); assert_eq!(parse_version("v1.2.3\nextra").as_deref(), Some("1.2.3"));}#[test]fn something_with_no_version_in_it_is_no_answer_at_all_never_a_zero() { assert_eq!(parse_version(""), None); assert_eq!(parse_version("command not found"), None); assert_eq!(parse_version("unknown"), None);}/// What a fake agent answered, from a fake path.fn answered(path: &str, said: &str) -> Found {Found { path: path.to_string(), said: said.to_string(), }}#[test]fn an_agent_that_is_not_installed_is_absent_from_the_map_not_an_empty_version() {let detected = installed_agents(|program| match program {"claude" => Some(answered("/Users/me/.local/bin/claude", "2.1.274 (Claude Code)")), _ => None, }); assert_eq!( detected.versions, BTreeMap::from([("claude-code".to_string(), "2.1.274".to_string())]) ); assert!( !detected.versions.contains_key("codex"),"an absent agent is absent — a dispatcher must be able to tell 'not installed' from 'version unknown'" ); assert!( !detected.found_at.contains_key("codex"),"and it was found nowhere" );}#[test]fn both_installed_is_both_in_the_map() {let detected = installed_agents(|program| match program {"claude" => Some(answered("/Users/me/.local/bin/claude", "2.1.274 (Claude Code)")),"codex" => Some(answered("/opt/homebrew/bin/codex", "codex-cli 0.55.0")), _ => None, }); assert_eq!( detected.versions, BTreeMap::from([ ("claude-code".to_string(), "2.1.274".to_string()), ("codex".to_string(), "0.55.0".to_string()), ]) );}#[test]fn npm_is_probed_beside_the_agents_because_the_panel_has_a_decision_to_make_about_it() {// Codex installs with `npm install -g @openai/codex`, so a Mac with no// Node is a Mac where that button would fail. The panel needs the answer// BEFORE it offers the button, and this is where the answer comes from.let with_node = installed_agents(|program| match program {"npm" => Some(answered("/opt/homebrew/bin/npm", "10.9.0")), _ => None, }); assert_eq!( with_node.versions, BTreeMap::from([("npm".to_string(), "10.9.0".to_string())]) );// And it is absent, never a zero, exactly as an agent is.let without = installed_agents(|_| None); assert!(!without.versions.contains_key("npm"));// It is not an agent and nothing may draw it as one: the two agent keys// are the ones a panel asks for by name. assert!(!EXTRA_PROGRAMS.contains(&"claude-code")); assert!(!EXTRA_PROGRAMS.contains(&"codex"));}#[test]fn an_agent_that_answered_nothing_a_version_reads_out_of_is_found_nowhere_either() {let detected = installed_agents(|_| Some(answered("/usr/bin/claude", "command not found"))); assert_eq!(detected, Detected::default());}#[test]fn the_log_line_names_the_binary_that_answered_because_which_one_is_the_question() {let detected = installed_agents(|program| match program {"claude" => Some(answered("/Users/me/.local/bin/claude", "2.1.274 (Claude Code)")), _ => None, });let said = describe(&detected); assert!(said.contains("claude-code 2.1.274"), "{said}"); assert!(said.contains("/Users/me/.local/bin/claude"), "{said}"); assert!( describe(&Detected::default()).contains("PATH"),"nothing found says what it looked at" );}#[test]fn an_agent_is_detected_against_the_captured_path_and_never_the_process_s_own() {usecrate::login_env::LoginEnv;use std::os::unix::fs::PermissionsExtas _;let dir = tempfile::tempdir().expect("a scratch directory");let claude = dir.path().join("claude"); std::fs::write(&claude, "#!/bin/shecho '9.9.9 (ClaudeCode)'").expect("written"); std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).expect("executable");// The PATH launchd hands this agent, which holds neither of them, plus the// one directory that does.let env = LoginEnv::from_vars(BTreeMap::from([("PATH".to_string(), format!("/usr/bin:/bin:/usr/sbin:/sbin:{}", dir.path().display()), )]));let detected = detect(&env); assert_eq!( detected.versions.get("claude-code").map(String::as_str),Some("9.9.9") ); assert_eq!( detected.found_at.get("claude-code").map(String::as_str),Some(claude.display().to_string().as_str()) );}#[test]fn linux_memory_comes_from_the_kernel_s_own_available_figure() {let meminfo = "MemTotal: 16318248 kB\nMemFree: 223116 kB\nMemAvailable: 8159124 kB\nBuffers: 102400 kB\n"; assert_eq!(parse_meminfo(meminfo), Some((16_318_248, 8_159_124))); assert_eq!(free_pct(8_159_124, 16_318_248), 50);}#[test]fn a_meminfo_missing_the_field_is_no_answer_rather_than_a_guess() { assert_eq!(parse_meminfo("MemTotal: 16318248 kB\n"), None); assert_eq!(parse_meminfo(""), None);}#[test]fn macos_free_memory_counts_the_pages_the_kernel_would_hand_over() {let vm_stat = concat!("Mach Virtual Memory Statistics: (page size of 16384 bytes)\n","Pages free: 10000.\n","Pages active: 200000.\n","Pages inactive: 30000.\n","Pages speculative: 5000.\n","Pages wired down: 50000.\n", ); assert_eq!(parse_vm_stat_free_pages(vm_stat), Some(45_000));}#[test]fn vm_stat_without_the_optional_lines_still_answers_from_what_is_there() {let vm_stat = "Pages free: 10000.\n"; assert_eq!(parse_vm_stat_free_pages(vm_stat), Some(10_000)); assert_eq!(parse_vm_stat_free_pages("Pages active: 1.\n"), None);}#[test]fn what_a_mac_is_using_is_the_kernel_s_own_figure_and_never_a_sum_of_processes() {// The number the budget starts from. Summed RSS counts every shared page// once per process and answered 37.9 GB on this 24 GB Mac; the kernel's// own free percentage does not.let mac = Memory { total_gb: 24.0, free_pct: 40, }; assert_eq!(mac.used_gb(), 14.4); assert_eq!(Memory { total_gb: 24.0, free_pct: 100 } .used_gb(),0.0 );// A memory reader that answered nothing reports zero free, and zero free// of zero total is zero used rather than a division. assert_eq!(Memory::default().used_gb(), 0.0);}#[test]fn a_percentage_is_whole_bounded_and_never_divides_by_a_zero_total() { assert_eq!(free_pct(0, 100), 0); assert_eq!(free_pct(100, 100), 100); assert_eq!(free_pct(1, 3), 33); assert_eq!(free_pct(2, 3), 67); assert_eq!(free_pct(5, 0), 0); assert_eq!(free_pct(200, 100), 100);}#[test]fn the_build_lock_is_held_only_when_its_holder_is_still_alive() {let dir = tempfile::tempdir().expect("a scratch directory");let lock = dir.path().join("tinmen-build.lock"); assert!(!build_lock_held(&lock), "no lock directory is no lock"); std::fs::create_dir_all(&lock).expect("creates the lock directory"); assert!(!build_lock_held(&lock), "a lock with no pid file is no lock"); std::fs::write(lock.join("pid"), format!("{}\n", std::process::id())).expect("writes the pid"); assert!(build_lock_held(&lock), "this process is alive, so the lock is held");// And the budget wants the HOLDER, not the bool: a pid is what names the// process tree that lock is standing in front of. assert_eq!(build_lock_pid(&lock), Some(std::process::id()));// A pid that cannot be a live process: `kill(2)` refuses 0 as a pid// meaning "this process group", so the parser answers None for it and the// lock reads as free rather than as held by the whole group. std::fs::write(lock.join("pid"), "not a pid\n").expect("writes rubbish"); assert!(!build_lock_held(&lock), "a pid file that is not a pid is not a holder");}#[test]fn a_pid_file_is_parsed_or_refused_and_never_guessed_at() { assert_eq!(parse_pid("1234\n"), Some(1234)); assert_eq!(parse_pid(" 99 "), Some(99)); assert_eq!(parse_pid(""), None); assert_eq!(parse_pid("\n"), None); assert_eq!(parse_pid("12 34"), None); assert_eq!(parse_pid("-1"), None);}#[test]fn a_sample_is_stamped_from_the_clock_it_was_given_never_from_the_wall() {let dir = tempfile::tempdir().expect("a scratch directory");let clock = FixedClock::at("2026-09-18T08:15:00Z");let reading = sample( &clock, dir.path(),3, BTreeMap::from([("claude-code".to_string(), "2.1.274".to_string())]), BTreeMap::new(),HandedIn { binary: SelfReport { fingerprint: "49a000-68d0f1c0".to_string(), update_pending: true, }, measured: Measured { memory: Memory { total_gb: 24.0, free_pct: 40, }, committed_gb: 21.5, session_peak_gb: Some(12.0), session_peak_samples: 4, }, facts: &Facts { chip: Some("Invented M9 Ultra".to_string()), os_version: Some("27.1".to_string()), disk_total_gb: Some(1862.5), }, }, ); assert_eq!(reading.sampled_at, "2026-09-18T08:15:00Z");// HANDED IN, the third of the kind: what the machine IS was read once at// `serve` start, and a sample carries it rather than re-reading it. assert_eq!(reading.chip.as_deref(), Some("Invented M9 Ultra")); assert_eq!(reading.os_version.as_deref(), Some("27.1")); assert_eq!(reading.disk_total_gb, Some(1862.5)); assert_eq!(reading.sessions_running, 3);// HANDED IN as well, and for the same reason: the caller walks the process// table because it is the only thing that knows which pids are its own// sessions, and `sample` assembles what it was given. ONE memory reading// goes in, so the free percentage and the committed figure computed from// it are the same instant. assert_eq!(reading.mem_free_pct, 40); assert_eq!(reading.mem_total_gb, 24.0); assert_eq!(reading.mem_committed_gb, 21.5); assert_eq!(reading.session_peak_gb, Some(12.0)); assert_eq!(reading.session_peak_samples, 4); assert_eq!(reading.host_version, crate::HOST_VERSION);// HANDED IN, never re-read: the identity is what the executable was when// `serve` started, and a sample that stat'ed the file itself would report// the replacement's fingerprint as though it were the running one. assert_eq!(reading.binary_fingerprint, "49a000-68d0f1c0"); assert!(reading.update_pending); assert!(reading.cpu_count >= 1, "a machine has at least one CPU"); assert!( reading.disk_free_gb > 0.0,"the volume the scratch directory is on has some space on it" );}#[test]fn free_disk_on_a_path_that_is_not_there_answers_zero_rather_than_panicking() { assert_eq!( free_disk_gb(Path::new("/nonexistent/cotton-session-host/volume")),0.0 );}#[test]fn the_facts_of_this_machine_are_read_once_and_a_missing_volume_is_not_said() {// The three constants, off the machine the test runs on: whatever this// machine is, a real volume has a size that is at least what is free on// it, and the chip and the OS either answer or say nothing — never a blank.let dir = tempfile::tempdir().expect("a scratch directory");let said = facts(dir.path());let (free, total) = disk_gb(dir.path()).expect("the scratch volume answers"); assert!(total >= free, "a volume is at least as large as its free space"); assert_eq!(said.disk_total_gb, Some(total));for text in [&said.chip, &said.os_version].into_iter().flatten() { assert!(!text.trim().is_empty(), "an answer is never a blank"); }// A volume that is not there has no size: `None`, never a zero, because a// zero-byte drive is a different (and false) fact. assert_eq!( facts(Path::new("/nonexistent/cotton-session-host/volume")).disk_total_gb,None ); assert_eq!(disk_gb(Path::new("/nonexistent/cotton-session-host/volume")), None);}#[test]fn the_linux_readers_parse_the_kernel_s_own_files_and_answer_nothing_for_a_blank() { assert_eq!( parse_cpuinfo_model("processor\t: 0\nvendor_id\t: GenuineIntel\nmodel name\t: Invented Xeon W-9\n\ processor\t: 1\nmodel name\t: Invented Xeon W-9\n" ) .as_deref(),Some("Invented Xeon W-9") ); assert_eq!(parse_cpuinfo_model("processor\t: 0\n"), None); assert_eq!(parse_cpuinfo_model("model name\t: \n"), None); assert_eq!( parse_os_release_pretty_name("NAME=\"Invented OS\"\nPRETTY_NAME=\"Invented OS 12.4 LTS\"\nID=invented\n") .as_deref(),Some("Invented OS 12.4 LTS") ); assert_eq!(parse_os_release_pretty_name("ID=invented\n"), None); assert_eq!(parse_os_release_pretty_name("PRETTY_NAME=\"\"\n"), None);}/// RULE: A machine samples itself exactly as often as the core says it reports — `SAMPLE_EVERY_SECONDS` is `REPORT_INTERVAL_MINUTES` times sixty.////// Until 30 Sep 2026 a Mac sampled every fifteen minutes and the seen window/// was built around that; the report is now every five, and the core's window/// (ten minutes) only holds if this timer keeps to the core's number.#[test]fn the_sample_cadence_is_the_report_interval_the_core_declares() {// The core's constant by name (cotton-core is a dev-dependency): a second// spelling of the number with nothing holding the two together is how the// seen window and the report drifted apart once already. Never read by// path — a crate cotton-ffi reaches reads no file outside its directory.let declared = u64::try_from(cotton_core::rules::machines::REPORT_INTERVAL_MINUTES) .expect("a positive interval"); assert_eq!(SAMPLE_EVERY_SECONDS, declared * 60); assert_eq!(SAMPLE_EVERY_SECONDS, 300);}// ── who is signed in ────────────────────────────────────────────────────────fn detected(agents: &[&str]) -> Detected {letmut found = Detected::default();for agent in agents { found .versions .insert((*agent).to_string(), "1.0.0".to_string()); found .found_at .insert((*agent).to_string(), format!("/opt/bin/{agent}")); } found}const SIGNED_IN: &str = r#"{"loggedIn": true, "email": "owner@example.com", "subscriptionType": "max"}"#;#[test]fn a_detected_agent_is_asked_who_is_signed_in_and_the_answer_is_keyed_by_the_agent() {let asked = std::cell::RefCell::new(Vec::new());let accounts = signed_in_agents(&detected(&["claude-code"]), |key, argv| { asked.borrow_mut().push((key.to_string(), argv.join(" ")));Some(SIGNED_IN.to_string()) }); assert_eq!( asked.into_inner(), vec![("claude-code".to_string(), "auth status".to_string())] ); assert_eq!(accounts.len(), 1); assert_eq!(accounts["claude-code"].email, "owner@example.com");}#[test]fn an_agent_that_is_not_installed_is_never_asked() {let accounts = signed_in_agents(&detected(&["npm"]), |key, _| { panic!("{key} was asked, and there is no binary to ask") }); assert!(accounts.is_empty());}#[test]fn codex_is_installed_and_still_not_asked() {let accounts = signed_in_agents(&detected(&["codex"]), |key, _| { panic!("{key} was asked, and its answer names nobody") }); assert!(accounts.is_empty());}#[test]fn an_agent_that_did_not_answer_or_is_signed_out_is_absent_from_the_map() {let silent = signed_in_agents(&detected(&["claude-code"]), |_, _| None); assert!(silent.is_empty());let signed_out = signed_in_agents(&detected(&["claude-code"]), |_, _| {Some(r#"{"loggedIn": false}"#.to_string()) }); assert!(signed_out.is_empty());}// ── can this Mac sign a release ─────────────────────────────────────────────/// What `security find-identity -v -p codesigning` prints on a Mac that can/// sign a release — invented, in the shape the real one has.const CAN_SIGN: &str = " 1) 1111111111111111111111111111111111111111 \ \"Apple Development: nobody@example.test (ZZ99YY88XX)\"\n \ 2) 0000000000000000000000000000000000000000 \ \"Developer ID Application: An Invented Company (AB12CD34EF)\"\n \ 2 valid identities found\n";/// RULE: A Mac can sign a release exactly when its keychain lists a VALID Developer ID Application identity — asked with `-v`, so an expired or revoked certificate is never one — and every other answer, an error included, is no.#[test]fn a_mac_can_sign_only_on_a_valid_developer_id_application_identity() { assert!( FIND_IDENTITY_ARGS.contains(&"-v"),"WITHOUT `-v` the listing carries expired identities, and a Mac whose certificate ran out \ would say it can sign and fail every release placed on it" ); assert_eq!(signing_identity(CAN_SIGN).as_deref(), Some("AB12CD34EF"));// An identity with no team in brackets is still an identity. assert_eq!( signing_identity(" 1) 0000 \"Developer ID Application: An Invented Company\"\n").as_deref(),Some("An Invented Company") );for listing in [" 1) 1111111111111111111111111111111111111111 \"Apple Development: nobody@example.test (ZZ99YY88XX)\"\n 1 valid identities found\n",""," 0 valid identities found\n","security: SecKeychainCopyDefault: A default keychain could not be found.\n", ] { assert_eq!(signing_identity(listing), None, "this Mac cannot sign a release: {listing:?}"); }}/// RULE: The keychain's answer has three states — it signs, it cannot, it did not say — and only a completed listing with no Developer ID identity is "cannot": a failed call or an error message is never read as a Mac that lost its certificate, because its runner row drops the signing label on "cannot".#[test]fn a_keychain_that_did_not_answer_is_not_a_keychain_that_cannot_sign() { assert_eq!(keychain_said(CAN_SIGN), Keychain::Signs("AB12CD34EF".to_string())); assert_eq!(keychain_said(CAN_SIGN).can_sign(), Some(true));for answered_none in [" 0 valid identities found\n"," 1) 1111111111111111111111111111111111111111 \"Apple Development: nobody@example.test (ZZ99YY88XX)\"\n 1 valid identities found\n", ] { assert_eq!(keychain_said(answered_none), Keychain::CannotSign, "{answered_none:?}"); } assert_eq!(Keychain::CannotSign.can_sign(), Some(false));for silent in ["","security: SecKeychainCopyDefault: A default keychain could not be found.\n", ] { assert_eq!(keychain_said(silent), Keychain::DidNotSay, "{silent:?}"); } assert_eq!(Keychain::DidNotSay.can_sign(), None); assert_eq!(Keychain::DidNotSay.team(), None);}/// RULE: A Mac says on its own sample whether it can sign a release — `developer-id` beside its programs when its keychain holds the identity, absent when it does not, under the key the core reads — because every Mac may build and only the machine can ask its keychain.#[test]fn a_mac_that_can_sign_says_so_beside_its_programs_and_one_that_cannot_says_nothing() {// The core's runner rules that read this key were retired with the runner// tables (TABLE DROP 1, 27 Nov 2026); the spelling stays the one they read. assert_eq!(SIGNING_IDENTITY_KEY, "developer-id");let programs = installed_agents(|program| match program {"claude" => Some(answered("/opt/homebrew/bin/claude", "2.1.274 (Claude Code)")), _ => None, });let signer = with_signing_identity(programs.clone(), signing_identity(CAN_SIGN)); assert_eq!( signer.versions.get(SIGNING_IDENTITY_KEY).map(String::as_str),Some("AB12CD34EF") );// The programs are untouched by it. assert_eq!(signer.versions.get("claude-code"), programs.versions.get("claude-code")); assert_eq!(with_signing_identity(programs.clone(), None), programs);}// RULE: Every sampler probe is bounded, including a descendant holding stdout after its parent exits; an unavailable agent must never stop disk samples.#[test]fn sampling_probes_bound_both_process_and_pipe_completion() {use std::time::{Duration, Instant};for script in ["exec sleep 30", "sleep 30 & printf 'version'; exit 0"] {letmut command = std::process::Command::new("/bin/sh"); command.args(["-c", script]);let started = Instant::now(); assert!(output_within(command, Duration::from_millis(40)).is_none()); assert!(started.elapsed() < Duration::from_secs(2)); }letmut command = std::process::Command::new("/bin/sh"); command.args(["-c", "printf 'signed out'; exit 1"]); assert_eq!( said_within(command, Duration::from_secs(1)).as_deref(),Some("signed out") );}/// RULE: A Linux report carries the shared hardware and capacity readings; app version, accounts and session peaks are absent because a tmux reporter owns no app or session trees.#[test]fn linux_report_keeps_hardware_and_capacity() {let sample = lane_sample(&crate::clock::FixedClock::at("2026-10-14T06:00:00Z"), std::path::Path::new("."), 3); assert_eq!(sample.sessions_running, 3);let columns = reading_columns(&sample); assert_eq!(columns["cpu_count"], sample.cpu_count); assert_eq!(columns["mem_total_gb"], sample.mem_total_gb); assert_eq!(columns["disk_free_gb"], sample.disk_free_gb); assert_eq!(columns["load1"], sample.load1); assert_eq!(columns["mem_free_pct"], sample.mem_free_pct); assert!(!columns.contains_key("app_version")); assert!(sample.accounts.is_empty()); assert!(sample.session_peak_gb.is_none()); assert!(sample.cpu_count > 0); assert!(sample.mem_total_gb > 0.0); assert!(sample.disk_total_gb.is_some_and(|total| total > 0.0)); assert!(sample.chip.as_ref().is_some_and(|chip| !chip.is_empty())); assert!(sample.os_version.as_ref().is_some_and(|version| !version.is_empty())); assert_eq!(columns["mem_committed_gb"], sample.mem_committed_gb); assert_eq!(columns["build_lock_held"], sample.build_lock_held); assert_eq!(columns["host_version"], sample.host_version); #[cfg(target_os = "linux")] assert!(sample.hardware_id.is_none(), "Linux has no Mac IOPlatform UUID");}/// RULE: A missed startup capacity probe is retried on the next kernel sample, so a running Mac cannot keep sending NULL capacity forever.#[test]fn a_sample_repairs_capacity_missing_at_startup() {let home = tempfile::tempdir().unwrap();let clock = FixedClock::at("2026-09-18T08:15:00Z");let facts = Facts { chip: None, os_version: None, disk_total_gb: None };let reading = sample(&clock, home.path(), 0, BTreeMap::new(), BTreeMap::new(), HandedIn { binary: SelfReport::default(), measured: Measured::default(), facts: &facts, }); assert_eq!(reading.disk_total_gb, disk_gb(home.path()).map(|(_, total)| total)); assert!(reading.disk_total_gb.is_some_and(|total| total > 0.0));}