Cotton code
900 lines · 31.3 KB · RustRaw
//! Every picking rule, one test each, the tie-break four ways, and every//! refusal's written sentence.//!//! Every Mac, login and key below is invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]), and `now` is an explicit//! instant rather than the wall clock.use chrono::{DateTime, Duration, Utc};use super::super::budget::JobKind;use super::*;const NOW: &str = "2026-09-18T09:00:00Z";fn now() -> DateTime<Utc> {    DateTime::parse_from_rfc3339(NOW)        .expect("a literal instant")        .with_timezone(&Utc)}fn ago(minutes: i64) -> Option<DateTime<Utc>> {    Some(now() - Duration::minutes(minutes))}/// A Mac with nothing wrong with it.fn free_mac(device_id: &str, name: &str) -> DeviceFacts {    DeviceFacts {        device_id: device_id.to_string(),        name: name.to_string(),        platform: Some("mac".to_string()),        host_version: Some("1.4.0".to_string()),        revoked: false,        sampled_at: ago(1),        sessions_running: 0,        sessions_cap: 3,        mem_free_pct: Some(60),        load1: Some(1.0),        mem_committed_gb: Some(2.0),        mem_budget_gb: Some(14.0),        session_peak: None,        agents: vec!["claude-code".to_string(), "codex".to_string()],        account: Some(AccountFacts {            email: "owner@example.test".to_string(),            five_hour_pct: Some(12.0),        }),        repos: None,        disk_free_gb: Some(400.0),        disk_total_gb: Some(926.0),        keep_free_bytes: None,    }}const TOOL: &str = "claude-code";/// One coding agent and nothing beside it — what most of these tests ask for.fn ask() -> Ask {    Ask::coding_session(0)}fn pick(devices: &[DeviceFacts]) -> Result<String, Refusal> {    pick_device(devices, TOOL, None, &ask(), now())}fn pick_for(devices: &[DeviceFacts], ask: &Ask) -> Result<String, Refusal> {    pick_device(devices, TOOL, None, ask, now())}/// The one per-Mac reason a single Mac gave for a particular ask.fn only_reason_for(devices: &[DeviceFacts], ask: &Ask) -> DeviceRefusal {    match pick_for(devices, ask).expect_err("a refusal") {        Refusal::EveryDeviceBusy(refused) => {            assert_eq!(refused.len(), 1, "one Mac, one reason");            refused[0].why.clone()        }        other => panic!("expected a per-Mac refusal, got {other:?}"),    }}fn refusal(devices: &[DeviceFacts]) -> Refusal {    pick(devices).expect_err("a refusal")}/// The one per-Mac reason a single-candidate list came back with.fn only_reason(devices: &[DeviceFacts]) -> DeviceRefusal {    match refusal(devices) {        Refusal::EveryDeviceBusy(refused) => {            assert_eq!(refused.len(), 1, "one Mac, one reason");            refused[0].why.clone()        }        other => panic!("expected a per-Mac refusal, got {other:?}"),    }}// ── the household ───────────────────────────────────────────────────────────#[test]fn a_household_with_no_mac_says_so_rather_than_listing_nobody() {    let refusal = pick(&[]).expect_err("a refusal");    assert_eq!(refusal, Refusal::NoDevices);    assert!(refusal.sentence(&[]).contains("No Mac has joined"));}#[test]fn any_mac_means_any_mac_and_nothing_gates_it() {    // There is no mode, no project switch and no household pause: a session    // the owner asked for with no Mac named is placed on whichever Mac is    // free. The whole of the old `manual`/`suggest`/`auto` question is gone.    assert_eq!(pick(&[free_mac("key-a", "mac-a")]), Ok("key-a".to_string()));}// ── one rule per test ───────────────────────────────────────────────────────#[test]fn a_revoked_mac_is_never_dispatched_to() {    let mut mac = free_mac("key-a", "mac-a");    mac.revoked = true;    let quiet = {        let mut quiet = free_mac("key-b", "mac-b");        quiet.sessions_running = 3;        quiet    };    assert_eq!(pick(&[mac.clone()]), Err(Refusal::NoDevices));    let reason = refusal(&[mac, quiet]).hold_reason(&[]);    assert!(!reason.contains("mac-a"), "a revoked Mac is not part of the household: {reason}");}/// A phone as the file holds one: admitted, never reported, no helper.fn phone(device_id: &str, name: &str) -> DeviceFacts {    DeviceFacts {        platform: Some("ios".to_string()),        host_version: None,        sampled_at: None,        sessions_running: 0,        mem_free_pct: None,        load1: None,        mem_committed_gb: None,        mem_budget_gb: None,        agents: Vec::new(),        account: None,        ..free_mac(device_id, name)    }}/// RULE: A device that cannot host a session — a phone that has never reported, or a revoked one — is never a candidate and is never named in a hold sentence.////// Todo 8ab33c0f: a queued card read "Waiting for a free Mac: iPhone has never/// reported — the session host is not running on it", which sent the owner to/// look for a session helper on a phone.#[test]fn a_device_that_cannot_host_is_never_a_candidate_nor_named_in_a_hold_sentence() {    let mut quiet = free_mac("key-a", "mac-b");    quiet.sampled_at = ago(SEEN_WINDOW_MINUTES + 20);    let reason = refusal(&[phone("key-p", "Example iPhone"), quiet]).hold_reason(&[]);    assert!(!reason.contains("iPhone"), "{reason}");    assert!(reason.contains("mac-b"), "{reason}");    // A household of phones is a household with no Mac.    assert_eq!(pick(&[phone("key-p", "Example iPhone")]), Err(Refusal::NoDevices));}#[test]fn a_mac_that_has_never_reported_is_still_a_host_and_says_it_has_never_reported() {    // Platform alone makes a Mac a host: the sentence about it is the one the    // owner can act on — start CottonDB there.    let mut mac = free_mac("key-a", "mac-a");    mac.sampled_at = None;    mac.host_version = None;    assert_eq!(only_reason(&[mac]), DeviceRefusal::NeverReported);}#[test]fn a_mac_that_has_never_reported_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.sampled_at = None;    assert_eq!(only_reason(&[mac]), DeviceRefusal::NeverReported);}#[test]fn a_mac_silent_for_longer_than_the_window_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.sampled_at = ago(SEEN_WINDOW_MINUTES + 31);    assert_eq!(        only_reason(&[mac]),        DeviceRefusal::NotSeenRecently {            minutes: SEEN_WINDOW_MINUTES + 31        }    );}/// RULE: A Mac that is reporting on time is never turned away for being quiet — the wait before a Mac reads as gone is longer than the gap between its own reports.////// From the first release to 27 Sep 2026 the window was ten minutes and a Mac/// reported every fifteen, so every healthy Mac was refused for the last/// third of every quarter of an hour. A Mac now reports every five.#[test]fn a_mac_whose_newest_reading_is_one_whole_interval_old_is_still_a_candidate() {    use crate::rules::machines::REPORT_INTERVAL_MINUTES;    const { assert!(SEEN_WINDOW_MINUTES > REPORT_INTERVAL_MINUTES) };    let mut mac = free_mac("key-a", "mac-a");    mac.sampled_at = ago(REPORT_INTERVAL_MINUTES);    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn a_mac_that_reported_exactly_on_the_window_is_still_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.sampled_at = ago(SEEN_WINDOW_MINUTES);    assert_eq!(        pick(&[mac]),        Ok("key-a".to_string()),        "the boundary is inside the window: a Mac reporting on its own tick must not fall out of \         the household on a rounding"    );}#[test]fn a_reading_from_the_future_is_not_a_silence() {    let mut mac = free_mac("key-a", "mac-a");    mac.sampled_at = Some(now() + Duration::minutes(5));    assert_eq!(        pick(&[mac]),        Ok("key-a".to_string()),        "two Macs' clocks disagree by seconds, and a skew must not read as a Mac that went away"    );}#[test]fn a_mac_at_its_cap_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.sessions_running = 3;    assert_eq!(        only_reason(&[mac]),        DeviceRefusal::AtCap { running: 3, cap: 3 }    );}#[test]fn a_mac_one_under_its_cap_is_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.sessions_running = 2;    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn a_cap_of_zero_takes_a_mac_out_of_the_household() {    let mut mac = free_mac("key-a", "mac-a");    mac.sessions_cap = 0;    assert_eq!(        only_reason(&[mac]),        DeviceRefusal::AtCap { running: 0, cap: 0 },        "the cap is the one switch left, and zero is what taking a Mac out looks like"    );}#[test]fn a_mac_that_has_not_said_how_much_memory_is_free_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_free_pct = None;    assert_eq!(only_reason(&[mac]), DeviceRefusal::MemoryUnknown);}#[test]fn a_mac_under_the_memory_floor_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_free_pct = Some(MIN_FREE_MEMORY_PCT - 1);    assert_eq!(only_reason(&[mac]), DeviceRefusal::LowMemory { free_pct: 24 });}#[test]fn a_mac_exactly_on_the_memory_floor_is_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_free_pct = Some(MIN_FREE_MEMORY_PCT);    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn a_mac_with_no_room_for_the_job_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_committed_gb = Some(13.8);    let why = only_reason_for(&[mac], &Ask::one(JobKind::XcodebuildArchive));    assert_eq!(        why,        DeviceRefusal::NoRoom {            free_gb: 0.2,            job: "build",            cost_gb: 8.0,        }    );    assert_eq!(        RefusedDevice {            device_id: "key-a".to_string(),            name: "mac-a".to_string(),            why,        }        .sentence(&[]),        "mac-a has 0.2 GB free; a build needs 8.0"    );}#[test]fn holding_the_build_lock_is_a_cost_and_not_a_refusal() {    // A 48 GB Mac used to turn away a 0.6 GB agent because somebody was    // compiling. What the build costs is inside `mem_committed_gb` now, and a    // Mac with room takes the session while the build runs.    let mut building = free_mac("key-a", "mac-a");    building.mem_committed_gb = Some(8.6);    assert_eq!(pick(&[building]), Ok("key-a".to_string()));}#[test]fn a_job_that_exactly_fills_the_remaining_budget_is_admitted() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_budget_gb = Some(10.0);    mac.mem_committed_gb = Some(9.4);    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn a_mac_over_its_budget_is_told_it_has_nothing_free() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_committed_gb = Some(20.0);    assert_eq!(        only_reason(&[mac]),        DeviceRefusal::NoRoom {            free_gb: 0.0,            job: "coding_session",            cost_gb: 0.6,        }    );}#[test]fn a_mac_that_has_reported_no_budget_is_still_dispatched_to() {    // A helper too old to measure is one the other checks still cover;    // refusing every Mac until each had been repackaged would empty the queue.    let mut mac = free_mac("key-a", "mac-a");    mac.mem_budget_gb = None;    mac.mem_committed_gb = None;    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn the_mac_s_own_measurement_decides_what_a_session_costs_there() {    // 1.4 GB measured beats the table's 0.6, and 13.0 committed of a 14.0    // budget leaves 1.0 — room for the guess, not for the measurement.    let mut mac = free_mac("key-a", "mac-a");    mac.mem_committed_gb = Some(13.0);    mac.session_peak = Some(Measured {        peak_gb: 1.4,        samples: 5,    });    assert_eq!(        only_reason(&[mac.clone()]),        DeviceRefusal::NoRoom {            free_gb: 1.0,            job: "coding_session",            cost_gb: 1.4,        }    );    // The same Mac, before it had watched three sessions: the table's guess.    mac.session_peak = Some(Measured {        peak_gb: 1.4,        samples: 2,    });    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn the_servers_a_session_opens_are_weighed_with_it() {    let mut mac = free_mac("key-a", "mac-a");    mac.mem_committed_gb = Some(13.0);    assert_eq!(pick_for(&[mac.clone()], &ask()), Ok("key-a".to_string()));    assert_eq!(        only_reason_for(&[mac], &Ask::coding_session(4)),        DeviceRefusal::NoRoom {            free_gb: 1.0,            job: "coding_session",            cost_gb: 1.8,        }    );}#[test]fn a_mac_without_the_tool_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.agents = vec!["codex".to_string()];    assert_eq!(        only_reason(&[mac]),        DeviceRefusal::ToolNotInstalled {            tool: "claude-code".to_string()        }    );}#[test]fn a_codex_session_asks_for_codex_and_nothing_else() {    let mut mac = free_mac("key-a", "mac-a");    mac.agents = vec!["claude-code".to_string()];    let refusal = pick_device(&[mac], "codex", None, &ask(), now()).expect_err("a refusal");    assert!(refusal.sentence(&[]).contains("codex"));}#[test]fn a_mac_with_the_tool_and_no_login_is_not_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.account = None;    assert_eq!(        only_reason(&[mac]),        DeviceRefusal::NotSignedIn {            tool: "claude-code".to_string()        }    );}#[test]fn a_login_at_or_past_the_limit_is_not_dispatched_into() {    for pct in [ACCOUNT_LIMIT_PCT, 97.5] {        let mut mac = free_mac("key-a", "mac-a");        mac.account = Some(AccountFacts {            email: "owner@example.test".to_string(),            five_hour_pct: Some(pct),        });        assert_eq!(            only_reason(&[mac]),            DeviceRefusal::AccountNearLimit {                account: "owner@example.test".to_string(),                pct            },            "the last tenth of a window is what a session the person started by hand finishes on"        );    }}#[test]fn a_login_just_under_the_limit_is_still_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.account = Some(AccountFacts {        email: "owner@example.test".to_string(),        five_hour_pct: Some(89.9),    });    assert_eq!(pick(&[mac]), Ok("key-a".to_string()));}#[test]fn a_login_with_no_reading_yet_is_a_candidate() {    let mut mac = free_mac("key-a", "mac-a");    mac.account = Some(AccountFacts {        email: "owner@example.test".to_string(),        five_hour_pct: None,    });    assert_eq!(        pick(&[mac]),        Ok("key-a".to_string()),        "a login nobody has run a session on cannot be near its limit, and refusing over a \         missing number would leave a fresh Mac undispatchable until somebody used it by hand"    );}// ── the tie-break ───────────────────────────────────────────────────────────#[test]fn the_freest_mac_wins_and_free_means_load() {    let mut idle = free_mac("key-b", "mac-b");    idle.load1 = Some(0.4);    let mut busy = free_mac("key-a", "mac-a");    busy.load1 = Some(6.2);    assert_eq!(pick(&[busy.clone(), idle.clone()]), Ok("key-b".to_string()));    // And the order the rows came back in changes nothing.    assert_eq!(pick(&[idle, busy]), Ok("key-b".to_string()));}#[test]fn a_lighter_load_outranks_more_free_memory() {    let mut roomy_busy = free_mac("key-a", "mac-a");    roomy_busy.mem_free_pct = Some(80);    roomy_busy.load1 = Some(8.0);    let mut tight_idle = free_mac("key-b", "mac-b");    tight_idle.mem_free_pct = Some(30);    tight_idle.load1 = Some(0.2);    assert_eq!(        pick(&[roomy_busy, tight_idle]),        Ok("key-b".to_string()),        "both Macs have room — the question the tie-break answers is which one is free NOW"    );}#[test]fn an_equal_load_goes_to_the_mac_with_more_free_memory() {    let mut roomy = free_mac("key-b", "mac-b");    roomy.mem_free_pct = Some(80);    let mut tight = free_mac("key-a", "mac-a");    tight.mem_free_pct = Some(30);    assert_eq!(pick(&[tight.clone(), roomy.clone()]), Ok("key-b".to_string()));    assert_eq!(pick(&[roomy, tight]), Ok("key-b".to_string()));}#[test]fn an_equal_load_and_memory_goes_to_the_mac_running_fewest_sessions() {    let mut busy = free_mac("key-a", "mac-a");    busy.sessions_running = 2;    let quiet = free_mac("key-b", "mac-b");    assert_eq!(pick(&[busy.clone(), quiet.clone()]), Ok("key-b".to_string()));    assert_eq!(pick(&[quiet, busy]), Ok("key-b".to_string()));}#[test]fn a_mac_that_reported_no_load_sorts_behind_every_mac_that_did() {    let mut unknown = free_mac("key-a", "mac-a");    unknown.load1 = None;    let mut heavy = free_mac("key-b", "mac-b");    heavy.load1 = Some(11.0);    assert_eq!(        pick(&[unknown.clone(), heavy.clone()]),        Ok("key-b".to_string()),        "a load nobody knows is not a Mac anybody can call free"    );    // …and it is still a candidate when it is the only one.    assert_eq!(pick(&[unknown]), Ok("key-a".to_string()));}#[test]fn two_identical_macs_are_settled_by_the_key_so_the_answer_is_total() {    let first = free_mac("key-a", "mac-a");    let second = free_mac("key-b", "mac-b");    assert_eq!(pick(&[first.clone(), second.clone()]), Ok("key-a".to_string()));    assert_eq!(        pick(&[second, first]),        Ok("key-a".to_string()),        "the worker and the phone read the same file and must show the same pick, whatever order \         the rows arrive in"    );}// ── the sentence written onto the row ───────────────────────────────────────#[test]fn every_busy_mac_is_named_with_its_own_reason_when_they_differ() {    let mut at_cap = free_mac("key-a", "mac-a");    at_cap.sessions_running = 3;    let mut silent = free_mac("key-b", "mac-b");    silent.sampled_at = ago(41);    let mut full_up = free_mac("key-c", "mac-e");    full_up.mem_committed_gb = Some(14.0);    let refusal = refusal(&[full_up, silent, at_cap]);    assert_eq!(        refusal.hold_reason(&[]),        "Waiting for a free Mac: mac-a is running 3 of its 3 · mac-b has not reported in 41 minutes \         · mac-e has 0.0 GB free; a coding session needs 0.6.",        "the reasons are ordered by the Mac's name, so the same file reads the same way twice"    );}#[test]fn one_answer_for_the_whole_household_when_every_mac_says_the_same_thing() {    let mut full_a = free_mac("key-a", "mac-c");    full_a.sessions_running = 3;    let mut full_b = free_mac("key-b", "mac-b");    full_b.sessions_running = 3;    assert_eq!(        refusal(&[full_a, full_b]).hold_reason(&[]),        "mac-b and mac-c are full (3 of 3).",        "three Macs saying one thing is one sentence, not three"    );    let mut full_a = free_mac("key-a", "mac-a");    full_a.mem_committed_gb = Some(14.0);    let mut full_b = free_mac("key-b", "mac-b");    full_b.mem_committed_gb = Some(14.0);    assert_eq!(        refusal(&[full_a, full_b]).hold_reason(&[]),        "mac-a and mac-b are out of room: 0.0 GB free, and a coding session needs 0.6.",        "the household form of this one keeps both numbers — 'every Mac is out of room' is \         what sent somebody to look at four Macs to find out how much room they had"    );    let mut no_login_a = free_mac("key-a", "mac-a");    no_login_a.account = None;    let mut no_login_b = free_mac("key-b", "mac-b");    no_login_b.account = None;    assert_eq!(        refusal(&[no_login_a, no_login_b]).hold_reason(&[]),        "No Mac has claude-code signed in."    );}#[test]fn two_macs_full_at_different_caps_are_not_one_sentence() {    let mut three = free_mac("key-a", "mac-a");    three.sessions_running = 3;    let mut one = free_mac("key-b", "mac-b");    one.sessions_cap = 1;    one.sessions_running = 1;    assert_eq!(        refusal(&[three, one]).hold_reason(&[]),        "Waiting for a free Mac: mac-a is running 3 of its 3 · mac-b is running 1 of its 1.",        "'full (3 of 3)' would be false of the Mac whose cap is one"    );}#[test]fn a_hold_reason_always_fits_the_column() {    // Sixteen Macs, refusing for two DIFFERENT reasons with long login names:    // no one sentence speaks for the household, so the per-Mac form is what is    // written — and the whole of it is far past the cap, so what lands is a    // sentence still: as many Macs as fit, and the count of the rest.    let mut devices: Vec<DeviceFacts> = Vec::new();    for index in 0..16 {        let mut mac = free_mac(            &format!("key-{index:02}"),            &format!("a-very-long-machine-name-{index:02}"),        );        if index % 2 == 0 {            mac.account = Some(AccountFacts {                email: format!("someone-with-a-long-address-{index:02}@example.test"),                five_hour_pct: Some(93.0 + f64::from(index)),            });        } else {            mac.mem_committed_gb = Some(14.0);        }        devices.push(mac);    }    let reason = refusal(&devices).hold_reason(&[]);    assert!(        reason.chars().count() <= HOLD_REASON_MAX,        "{} characters: {reason}",        reason.chars().count()    );    assert!(reason.ends_with(" more."), "{reason}");    assert!(        reason.starts_with("Waiting for a free Mac: a-very-long-machine-name-00"),        "{reason}"    );}#[test]fn a_grouped_reason_is_capped_too() {    // Forty Macs, all at the same cap: naming every one of them would run past    // the column, so the fallback is the per-Mac form, itself capped.    let devices: Vec<DeviceFacts> = (0..40)        .map(|index| {            let mut mac = free_mac(                &format!("key-{index:02}"),                &format!("machine-number-{index:02}"),            );            mac.sessions_running = 3;            mac        })        .collect();    let reason = refusal(&devices).hold_reason(&[]);    assert!(        reason.chars().count() <= HOLD_REASON_MAX,        "{} characters: {reason}",        reason.chars().count()    );    assert!(reason.ends_with('.'), "{reason}");}#[test]fn no_refusal_is_ever_silent() {    // Every variant spells itself. A queue that goes quiet is the failure this    // design is most afraid of, so there is nothing here that reads as "".    let variants = [        Refusal::NoDevices,        Refusal::EveryDeviceBusy(vec![RefusedDevice {            device_id: "key-a".to_string(),            name: "mac-a".to_string(),            why: DeviceRefusal::NoRoom {                free_gb: 0.4,                job: "coding_session",                cost_gb: 0.6,            },        }]),    ];    for refusal in variants {        for sentence in [refusal.sentence(&[]), refusal.hold_reason(&[])] {            assert!(sentence.len() > 15, "{refusal:?} says {sentence:?}");            assert!(sentence.ends_with('.') || sentence.ends_with('?'), "{sentence:?}");            assert!(sentence.chars().count() <= HOLD_REASON_MAX, "{sentence:?}");        }    }    let per_device = [        DeviceRefusal::Revoked,        DeviceRefusal::NeverReported,        DeviceRefusal::NotSeenRecently { minutes: 41 },        DeviceRefusal::AtCap { running: 3, cap: 3 },        DeviceRefusal::MemoryUnknown,        DeviceRefusal::LowMemory { free_pct: 11 },        DeviceRefusal::NoRoom {            free_gb: 0.4,            job: "coding_session",            cost_gb: 0.6,        },        DeviceRefusal::ToolNotInstalled {            tool: "codex".to_string(),        },        DeviceRefusal::NotSignedIn {            tool: "codex".to_string(),        },        DeviceRefusal::AccountNearLimit {            account: "owner@example.test".to_string(),            pct: 94.0,        },    ];    for why in per_device {        assert!(why.sentence(&[]).len() > 10, "{why:?} says nothing");        // And the household form of each — one Mac and three — is a sentence        // that fits, because it is what the worker writes.        for names in ["mac-a", "mac-a, mac-b and mac-e"] {            let household = why.household_sentence(&[], names, 3);            assert!(household.chars().count() <= HOLD_REASON_MAX, "{household}");            assert!(                household.ends_with('.') || household.ends_with('?'),                "{household}"            );        }    }}#[test]fn a_placed_session_nobody_picked_up_says_which_mac_and_what_to_check() {    let reason = unclaimed_reason(&[], "mac-b");    assert_eq!(        reason,        "mac-b has not picked it up — is CottonDB running there?"    );    assert!(reason.chars().count() <= HOLD_REASON_MAX);}#[test]fn the_names_read_the_way_a_person_says_them() {    assert_eq!(listed(&[], &[]), "");    assert_eq!(listed(&[], &["mac-a".to_string()]), "mac-a");    assert_eq!(listed(&[], &["mac-a".to_string(), "mac-b".to_string()]), "mac-a and mac-b");    assert_eq!(        listed(&[], &["mac-a".to_string(), "mac-b".to_string(), "mac-c".to_string()]),        "mac-a, mac-b and mac-c"    );}// ── the code ────────────────────────────────────────────────────────────────const REPO: &str = "asha.relay.cottondb.test/git/owner/thing";fn pick_in(devices: &[DeviceFacts], repo: Option<&str>) -> Result<String, Refusal> {    pick_device(devices, TOOL, repo, &ask(), now())}fn holding(mut mac: DeviceFacts, repos: &[&str]) -> DeviceFacts {    mac.repos = Some(repos.iter().map(|repo| (*repo).to_string()).collect());    mac}/// RULE: A session is never placed on a Mac that has neither the code nor a copy to make it from — it goes to a Mac that has it.#[test]fn a_session_goes_to_the_mac_that_has_its_repository_and_not_to_the_freer_one_that_does_not() {    let mut freer = holding(free_mac("key-a", "mac-a"), &["https://git.example.test/owner/other"]);    freer.load1 = Some(0.1);    let mut busier = holding(        free_mac("key-b", "mac-d"),        &["https://asha.relay.cottondb.test/git/owner/thing"],    );    busier.load1 = Some(3.0);    assert_eq!(pick_in(&[freer, busier], Some(REPO)), Ok("key-b".to_string()));}#[test]fn the_session_s_address_and_the_mac_s_are_compared_in_one_spelling() {    let mac = holding(        free_mac("key-a", "mac-a"),        &["https://asha.relay.cottondb.test/git/owner/thing"],    );    for spelling in [        "asha.relay.cottondb.test/git/owner/thing",        "https://asha.relay.cottondb.test/git/owner/thing.git",        "https://someone@asha.relay.cottondb.test/git/owner/thing/",    ] {        assert_eq!(            pick_in(std::slice::from_ref(&mac), Some(spelling)),            Ok("key-a".to_string()),            "{spelling}"        );    }}#[test]fn a_mac_that_looked_and_holds_none_is_refused_by_the_repository_s_own_name() {    let mac = holding(free_mac("key-a", "mac-a"), &[]);    match pick_in(&[mac], Some(REPO)).expect_err("a refusal") {        Refusal::EveryDeviceBusy(refused) => {            assert_eq!(                refused[0].why,                DeviceRefusal::RepoNotHere {                    repo: "thing".to_string()                }            );            assert_eq!(                refused[0].why.sentence(&[]),                "does not have thing and holds no copy to make one from"            );        }        other => panic!("{other:?}"),    }}#[test]fn a_mac_that_has_not_said_what_it_holds_is_still_a_candidate() {    // A helper too old to report. Refusing it would empty the queue until    // every Mac had been repackaged.    assert_eq!(        pick_in(&[free_mac("key-a", "mac-a")], Some(REPO)),        Ok("key-a".to_string())    );}#[test]fn a_session_that_names_no_repository_asks_nothing_about_the_code() {    let mac = holding(free_mac("key-a", "mac-a"), &[]);    assert_eq!(pick_in(&[mac], None), Ok("key-a".to_string()));}#[test]fn every_mac_without_the_repository_is_one_sentence_for_the_household() {    let first = holding(free_mac("key-a", "mac-a"), &[]);    let second = holding(free_mac("key-b", "mac-d"), &[]);    let said = pick_in(&[first, second], Some(REPO))        .expect_err("a refusal")        .hold_reason(&[]);    assert!(        said.contains("No Mac has thing, or a copy to make one from."),        "{said}"    );}#[test]fn a_mac_that_is_also_signed_out_says_that_first_because_it_is_the_one_to_fix_there() {    let mut mac = holding(free_mac("key-a", "mac-a"), &[]);    mac.account = None;    match pick_in(&[mac], Some(REPO)).expect_err("a refusal") {        Refusal::EveryDeviceBusy(refused) => assert_eq!(            refused[0].why,            DeviceRefusal::NotSignedIn {                tool: TOOL.to_string()            }        ),        other => panic!("{other:?}"),    }}/// RULE (P5): A session's candidate Macs are read from MINE's device rows, by/// id, whichever database queued it — never from that database's, and with no Mine/// recorded it is a named refusal, not a fallback.#[test]fn machines_are_read_from_mine_whatever_database_queued_the_session() {    assert_eq!(machines_database(Some("mine"), "mine"), Ok("mine"));    assert_eq!(machines_database(Some("mine"), "another-database"), Ok("mine"));    let refused = machines_database(None, "another-database").expect_err("no Mine, no list of Macs");    assert_eq!(refused, Refusal::NoOwnDatabase);    assert!(refused.hold_reason(&[]).chars().count() <= HOLD_REASON_MAX);    assert!(refused.hold_reason(&[]).contains("no database of its own"));}/// RULE: A lane's disk must fit above the same device floor media, jobs and cache trimming use; a raised floor cannot be ignored by the scheduler.#[test]fn a_lane_goes_only_where_its_disk_fits_over_the_reserve() {    let mut mac = free_mac("synthetic", "Synthetic Mac");    mac.disk_total_gb = Some(1000.0);    mac.disk_free_gb = Some(175.0);    assert!(pick(&[mac.clone()]).is_ok());    mac.disk_free_gb = Some(174.0);    assert!(pick(&[mac.clone()]).is_err());    mac.disk_free_gb = Some(225.0);    mac.keep_free_bytes = Some(200 * 1_073_741_824);    assert!(pick(&[mac.clone()]).is_ok());    mac.disk_free_gb = Some(224.0);    assert!(pick(&[mac]).is_err());}/// RULE: a held card's sentence is said in the database's own `dispatch`/// lines — a row rewords it with no build, and a line the database has no/// row for is the kit's (contract item 3: every sentence is a line).#[test]fn a_held_cards_sentence_is_said_in_the_databases_lines() {    let row = |line: &str, words: &str| LineRow { set: LINES.into(), line: line.into(), words: words.into() };    assert_eq!(        Refusal::NoDevices.hold_reason(&[row("no_devices", "No Mac yet.")]),        "No Mac yet."    );    assert_eq!(unclaimed_reason(&[row("unclaimed", "{machine} is quiet.")], "mac-b"), "{machine} is quiet.".replace("{machine}", "mac-b"));    assert_eq!(Refusal::NoOwnDatabase.hold_reason(&[]), shell_lines::resolve(LINES, "no_own_database", &[], &[]).unwrap());    let full = |name: &str| RefusedDevice {        device_id: name.into(),        name: name.into(),        why: DeviceRefusal::AtCap { running: 3, cap: 3 },    };    assert_eq!(Refusal::EveryDeviceBusy(vec![full("mac-a")]).hold_reason(&[]), "mac-a is full (3 of 3).");    assert_eq!(Refusal::EveryDeviceBusy(vec![full("mac-a"), full("mac-b")]).hold_reason(&[]), "mac-a and mac-b are full (3 of 3).");}