Cotton code
768 lines · 34.5 KB · RustRaw
//! Which Mac a queued session goes to — the whole of the decision, as a//! function of its arguments.//!//! **Cotton hosts and schedules; it never orchestrates**//! ([cotton-hosts-and-schedules-coding-sessions-it-never-builds-an-or]). This//! module is the SCHEDULING half and nothing more: given what each Mac is like//! right now and which agent a session asked for, it answers one device id —//! or a refusal that says, in a sentence a person can read on the card, why no//! Mac could take the work.//!//! **Every refusal carries its own sentence.** A queue that goes quiet is the//! failure this design is most afraid of: a person hands a todo to an agent,//! nothing happens, and there is nowhere to look. So there is no `None` here//! and no boolean — [`Refusal`] is an enum whose every variant spells itself,//! [`DeviceRefusal`] does the same per Mac, and [`Refusal::hold_reason`] is the//! ONE sentence the worker writes onto the row so that the card can say//! *"mac-b and mac-c are full (3 of 3)"* rather than *"queued"*.//!//! **THERE ARE NO DISPATCH MODES.** A session with no Mac named on it means//! "any Mac", and that is the whole of the question this module is asked. The//! `manual`/`suggest`/`auto` mode per project, and the two pause switches that//! went with it, were three ways of saying "do not place this" for a queue//! whose rows the owner had already asked for — so a queued session sat there//! with nothing wrong and nothing to read. The owner picks a Mac when they//! care and leaves it blank when they do not (Cotton note "The Code tool — why a Mac holds the sessions").//!//! **A MAC IS ADMITTED BY ITS BUDGET, NOT BY A LOCK.** What a job costs and//! what a Mac may promise are [`super::budget`]'s; the one place they are put//! together is [`refuse`], and the sentence that comes out of it names both//! numbers — *"mac-a has 0.4 GB free; a coding session needs 0.6"*. What stood//! there before was `build_lock_held`: a boolean that turned a 48 GB machine//! away from a 0.6 GB agent because somebody was compiling. The lock is still//! taken and still reported; what it is COSTING is measured and sits in the//! Mac's committed total (Cotton note "Repo landmines — why the build's rules exist").//!//! No clock, no database, no `Ctx`: [`pick_device`] takes the facts and `now`,//! which is what lets `dispatch_tests.rs` state every rule as arithmetic. The//! worker that READS those facts out of the file lives in `cotton-server`; the//! rule about which Mac wins lives here, once, so the phone can show the same//! answer the worker acted on.use chrono::{DateTime, Utc};use super::budget::{admits, cost_as_said, free_as_said, free_gb, Ask, Measured, LANE_DISK_GB};use super::machines::{can_host, report_state_at, ReportState};use super::shell_lines::{self, LineRow};/// How recently a Mac must have reported to be dispatched to — the ONE seen/// window, defined in [`super::machines`] and read here, by `rules::ci`, and/// by the phone's Settings › Code rows.////// **Ten minutes, because a Mac now reports every five**/// ([`super::machines::REPORT_INTERVAL_MINUTES`]) and the window is that/// interval plus five minutes' grace. A Mac that has said nothing for ten has/// missed its most recent report: it is asleep, off, or unable to reach the/// server, and a session placed on it would sit in `queued` until somebody/// noticed.////// The history, so nobody shortens it back by accident: it was ten until/// 27 Sep 2026 against a FIFTEEN-minute report, so every healthy Mac was/// refused as "has not reported in N minutes" for the last five minutes of/// every fifteen. It then became twenty (fifteen plus the grace), which was/// honest but slow to notice a Mac that had gone to sleep. The report/// interval came down to five instead, and the window with it. It is still/// WRITTEN AS the interval plus the grace, so the two cannot drift apart.pub use super::machines::SEEN_WINDOW_MINUTES;/// The free memory a Mac must have before another session lands on it.////// **Twenty-five per cent.** A coding agent's session is a compiler and a test/// run away from wanting several gigabytes, and the machine is also the one the/// person is using. Below a quarter free, adding a session is how a Mac starts/// swapping.pub const MIN_FREE_MEMORY_PCT: i64 = 25;/// How much of an account's five-hour window may be spent before the dispatcher/// stops sending it work.////// **Ninety per cent.** The last tenth is what a session the person started by/// hand should get to finish on. Dispatching into it is how an automatic launch/// takes the window a deliberate one was relying on.pub const ACCOUNT_LIMIT_PCT: f64 = 90.0;/// The ceiling on a written hold reason — `cotton_sessions.hold_reason`'s own/// CHECK, spelled here because this module is what writes one.////// **Two hundred characters.** It is a sentence on a card, not a log line: past/// this it stops being read at all, and the honest thing is to name the first/// few Macs and count the rest.pub const HOLD_REASON_MAX: usize = 200;/// The agent login a Mac is signed in as, for the tool a session asked for.#[derive(Debug, Clone, PartialEq)]pub struct AccountFacts {    /// The login's email address — the only thing about an account a refusal    /// ever names: never a label somebody typed, never a row id.    pub email: String,    /// The five-hour window, as the agent's own status line last reported it.    /// `None` is "no reading yet", which is not a refusal: a login nobody has    /// run a session on cannot be near its limit.    pub five_hour_pct: Option<f64>,}/// One Mac, as the dispatcher sees it.////// Every field is a column of `cotton_devices` or a derivation of one. The/// caller resolves `account` for the session's own tool before calling, because/// which login serves which tool is a mapping the file holds and this module/// deliberately does not.#[derive(Debug, Clone, PartialEq)]pub struct DeviceFacts {    /// The device key — what `device_id` on the session ends up holding.    pub device_id: String,    /// What the person calls this Mac. Refusals name it.    pub name: String,    /// `cotton_devices.platform` — `mac`, `linux`, `ios`, `android`, or    /// `None` for a row that never said. With `host_version` and `sampled_at`    /// it decides [`super::machines::can_host`].    pub platform: Option<String>,    /// The session helper's version, as the device last reported it. Only a    /// machine running the helper writes one.    pub host_version: Option<String>,    /// Cut off from the database. A revoked device cannot host    /// ([`super::machines::can_host`]), so it is never a candidate and never    /// named in a hold sentence.    pub revoked: bool,    /// When the helper on this Mac last reported. `None` is a Mac that has    /// never run one.    pub sampled_at: Option<DateTime<Utc>>,    pub sessions_running: i64,    pub sessions_cap: i64,    /// `None` is "never reported", which fails the check: a Mac whose memory is    /// unknown is one this cannot promise has room.    pub mem_free_pct: Option<i64>,    /// The one-minute load average, which is what ORDERS the Macs that pass:    /// the freest takes the work. `None` is "not reported", which does not    /// refuse a Mac — it only loses it the tie-break, because a Mac whose load    /// nobody knows is not a Mac anybody can call free.    pub load1: Option<f64>,    /// What this Mac has already promised, in gigabytes — the measured peaks    /// of the sessions Cotton started, plus what holds the build lock and the    /// heavy work beside it. `None` is "never reported", which does not refuse    /// a Mac: a helper too old to measure is one the checks above still cover,    /// and refusing every Mac until each had been repackaged would empty the    /// queue over a number nobody had asked for yet.    pub mem_committed_gb: Option<f64>,    /// What this Mac may promise in total — its memory less its reserve,    /// larger on the Mac holding the served file    /// ([`super::budget::budget_gb`]). `None` reads the same way as an    /// unreported commitment.    pub mem_budget_gb: Option<f64>,    /// What a coding session has actually been measured costing ON THIS MAC,    /// which beats the cost table's guess from three readings on    /// ([`super::budget::MEASURED_MINIMUM_SAMPLES`]).    pub session_peak: Option<Measured>,    /// The agent tools installed on this Mac, by the id a session names    /// (`claude-code`, `codex`).    pub agents: Vec<String>,    /// The login this Mac is signed in as for the session's tool, if any.    pub account: Option<AccountFacts>,    /// The repositories this Mac can start a session in, as canonical URLs    /// ([`super::repo_ref::canonical_repo_url`]) — one it has a folder for, or    /// one it holds the bytes of and can make a folder for. `None` is a Mac    /// that has NOT SAID, which does not refuse it: a helper too old to report    /// is covered by every check above, and refusing every Mac until each had    /// been repackaged would empty the queue — `mem_committed_gb`'s rule.    pub repos: Option<Vec<String>>,    /// `cotton_devices.disk_free_gb` and `disk_total_gb`. `None` is "not    /// reported", which does not refuse a Mac — `mem_committed_gb`'s rule.    pub disk_free_gb: Option<f64>,    pub disk_total_gb: Option<f64>,    pub keep_free_bytes: Option<u64>,}/// Why ONE Mac could not take this session.#[derive(Debug, Clone, PartialEq)]pub enum DeviceRefusal {    Revoked,    NeverReported,    NotSeenRecently { minutes: i64 },    AtCap { running: i64, cap: i64 },    MemoryUnknown,    LowMemory { free_pct: i64 },    NoRoom {        free_gb: f64,        job: &'static str,        cost_gb: f64,    },    ToolNotInstalled { tool: String },    NotSignedIn { tool: String },    AccountNearLimit { account: String, pct: f64 },    /// A new lane would take this Mac's disk under the reserve it keeps    /// ([`super::budget::disk_reserve_gb`]). Both figures are whole gigabytes,    /// as the sentence says them.    LowDisk { free_gb: f64, reserve_gb: f64 },    /// This Mac has looked, and it has neither a folder for the session's    /// repository nor the bytes to make one. `repo` is the repository's own    /// name — what a person reads — never the whole URL.    RepoNotHere { repo: String },}impl DeviceRefusal {    /// The sentence, without the Mac's name — [`RefusedDevice::sentence`] puts    /// the name in front of it — in `lines`' words (`dispatch.mac.*`).    #[must_use]    pub fn sentence(&self, lines: &[LineRow]) -> String {        let min_pct = MIN_FREE_MEMORY_PCT.to_string();        let lane_gb = format!("{LANE_DISK_GB:.0}");        match self {            DeviceRefusal::Revoked => say(lines, "mac.revoked", &[]),            DeviceRefusal::NeverReported => say(lines, "mac.never_reported", &[]),            DeviceRefusal::NotSeenRecently { minutes } => {                say(lines, "mac.not_seen", &[("minutes", &minutes.to_string())])            }            DeviceRefusal::AtCap { running, cap } => say(                lines,                "mac.at_cap",                &[("running", &running.to_string()), ("cap", &cap.to_string())],            ),            DeviceRefusal::MemoryUnknown => say(lines, "mac.memory_unknown", &[]),            DeviceRefusal::LowMemory { free_pct } => say(                lines,                "mac.low_memory",                &[("free_pct", &free_pct.to_string()), ("min_pct", &min_pct)],            ),            DeviceRefusal::NoRoom {                free_gb,                job,                cost_gb,            } => say(                lines,                "mac.no_room",                &[                    ("free_gb", &format!("{free_gb:.1}")),                    ("job", &say(lines, &format!("jobs.{job}"), &[])),                    ("cost_gb", &format!("{cost_gb:.1}")),                ],            ),            DeviceRefusal::ToolNotInstalled { tool } => say(lines, "mac.tool_not_installed", &[("tool", tool)]),            DeviceRefusal::LowDisk { free_gb, reserve_gb } => say(                lines,                "mac.low_disk",                &[                    ("free_gb", &format!("{free_gb:.0}")),                    ("lane_gb", &lane_gb),                    ("reserve_gb", &format!("{reserve_gb:.0}")),                ],            ),            DeviceRefusal::NotSignedIn { tool } => say(lines, "mac.not_signed_in", &[("tool", tool)]),            DeviceRefusal::AccountNearLimit { account, pct } => say(                lines,                "mac.account_near_limit",                &[("account", account), ("pct", &format!("{pct:.0}"))],            ),            DeviceRefusal::RepoNotHere { repo } => say(lines, "mac.repo_not_here", &[("repo", repo)]),        }    }    /// Do two refusals say the SAME thing about two different Macs?    ///    /// Used only by [`Refusal::hold_reason`], to decide whether the household's    /// answer can be told once. Where the numbers are part of what makes the    /// sentence true they have to match too — two Macs "full" at 3 of 3 and at    /// 1 of 1 are not one sentence.    fn same_as(&self, other: &DeviceRefusal) -> bool {        match (self, other) {            (DeviceRefusal::Revoked, DeviceRefusal::Revoked)            | (DeviceRefusal::NeverReported, DeviceRefusal::NeverReported)            | (DeviceRefusal::NotSeenRecently { .. }, DeviceRefusal::NotSeenRecently { .. })            | (DeviceRefusal::MemoryUnknown, DeviceRefusal::MemoryUnknown)            | (DeviceRefusal::LowMemory { .. }, DeviceRefusal::LowMemory { .. })            | (DeviceRefusal::AccountNearLimit { .. }, DeviceRefusal::AccountNearLimit { .. }) => {                true            }            (                DeviceRefusal::AtCap { running, cap },                DeviceRefusal::AtCap {                    running: other_running,                    cap: other_cap,                },            ) => running == other_running && cap == other_cap,            // THE FREE FIGURE IS PART OF WHAT MAKES THE SENTENCE TRUE, so two            // Macs with different room left are not one sentence — the same            // rule `AtCap` follows. Both numbers are already rounded to a            // tenth by `refuse`, so this compares what is printed.            (                DeviceRefusal::NoRoom {                    free_gb,                    job,                    cost_gb,                },                DeviceRefusal::NoRoom {                    free_gb: other_free,                    job: other_job,                    cost_gb: other_cost,                },            ) => free_gb == other_free && job == other_job && cost_gb == other_cost,            (                DeviceRefusal::ToolNotInstalled { tool },                DeviceRefusal::ToolNotInstalled { tool: other },            )            | (DeviceRefusal::NotSignedIn { tool }, DeviceRefusal::NotSignedIn { tool: other }) => {                tool == other            }            (DeviceRefusal::RepoNotHere { repo }, DeviceRefusal::RepoNotHere { repo: other }) => {                repo == other            }            (                DeviceRefusal::LowDisk { free_gb, reserve_gb },                DeviceRefusal::LowDisk { free_gb: other_free, reserve_gb: other_reserve },            ) => free_gb == other_free && reserve_gb == other_reserve,            _ => false,        }    }    /// The household's answer when EVERY Mac gave this one — the sentence with    /// no Mac's name in it, or with `names` where naming them is what makes it    /// readable — in `lines`' words (`dispatch.household.*`). A line that    /// differs by how many Macs is picked by `count`, as `{n}`.    fn household_sentence(&self, lines: &[LineRow], names: &str, count: usize) -> String {        let n = count.to_string();        let min_pct = MIN_FREE_MEMORY_PCT.to_string();        let lane_gb = format!("{LANE_DISK_GB:.0}");        match self {            DeviceRefusal::Revoked => say(lines, "household.revoked", &[]),            DeviceRefusal::NeverReported => say(lines, "household.never_reported", &[]),            DeviceRefusal::NotSeenRecently { .. } => say(                lines,                "household.not_seen",                &[("window", &SEEN_WINDOW_MINUTES.to_string()), ("names", names)],            ),            DeviceRefusal::AtCap { running, cap } => say(                lines,                "household.at_cap",                &[("n", &n), ("names", names), ("running", &running.to_string()), ("cap", &cap.to_string())],            ),            DeviceRefusal::MemoryUnknown => say(lines, "household.memory_unknown", &[]),            DeviceRefusal::LowMemory { .. } => {                say(lines, "household.low_memory", &[("n", &n), ("min_pct", &min_pct)])            }            // NAMED, and with both numbers — the household form of this one            // is the per-Mac form with the names in front, because "every Mac            // is out of room" is the sentence that sent somebody to look at            // four Macs to find out how much room they actually had.            DeviceRefusal::NoRoom {                free_gb,                job,                cost_gb,            } => say(                lines,                "household.no_room",                &[                    ("n", &n),                    ("names", names),                    ("free_gb", &format!("{free_gb:.1}")),                    ("job", &say(lines, &format!("jobs.{job}"), &[])),                    ("cost_gb", &format!("{cost_gb:.1}")),                ],            ),            DeviceRefusal::ToolNotInstalled { tool } => say(lines, "household.tool_not_installed", &[("tool", tool)]),            DeviceRefusal::NotSignedIn { tool } => say(lines, "household.not_signed_in", &[("tool", tool)]),            DeviceRefusal::AccountNearLimit { .. } => say(                lines,                "household.account_near_limit",                &[("n", &n), ("pct", &format!("{ACCOUNT_LIMIT_PCT:.0}"))],            ),            DeviceRefusal::RepoNotHere { repo } => say(lines, "household.repo_not_here", &[("repo", repo)]),            DeviceRefusal::LowDisk { free_gb, reserve_gb } => say(                lines,                "household.low_disk",                &[                    ("n", &n),                    ("names", names),                    ("free_gb", &format!("{free_gb:.0}")),                    ("lane_gb", &lane_gb),                    ("reserve_gb", &format!("{reserve_gb:.0}")),                ],            ),        }    }}/// The line set every sentence here is said in (`kits/shell/lines/dispatch.json`).pub const LINES: &str = "dispatch";/// One line of [`LINES`] — the database's row first, the kit's words for one/// it has none of — filled. A line the kit does not ship says its own path, so/// a missing line is seen rather than said as nothing.fn say(lines: &[LineRow], line: &str, fills: &[(&str, &str)]) -> String {    shell_lines::resolve(LINES, line, lines, fills).unwrap_or_else(|| format!("{LINES}.{line}"))}/// `a`, `a and b`, `a, b and c` — the names, as a person would say them.fn listed(lines: &[LineRow], names: &[String]) -> String {    match names {        [] => String::new(),        [only] => only.clone(),        [first, second] => say(lines, "names.two", &[("first", first), ("second", second)]),        [rest @ .., last] => {            let comma = say(lines, "names.comma", &[]);            say(lines, "names.many", &[("rest", &rest.join(&comma)), ("last", last)])        }    }}/// One Mac and the reason it was passed over.#[derive(Debug, Clone, PartialEq)]pub struct RefusedDevice {    pub device_id: String,    pub name: String,    pub why: DeviceRefusal,}impl RefusedDevice {    #[must_use]    pub fn sentence(&self, lines: &[LineRow]) -> String {        say(lines, "mac.said", &[("name", &self.name), ("why", &self.why.sentence(lines))])    }}/// Why no Mac took this session.#[derive(Debug, Clone, PartialEq)]pub enum Refusal {    /// There is no Mac in this database at all — the person has not joined one.    NoDevices,    /// The server holding the session records no database of the owner's own    /// — and the Macs that run sessions are devices of THAT database    /// ([`machines_database`]), never of another database's.    NoOwnDatabase,    /// There are Macs, and every one of them said no.    EveryDeviceBusy(Vec<RefusedDevice>),}impl Refusal {    /// The sentence the worker writes onto `cotton_sessions.hold_reason`, and    /// the card reads.    ///    /// **It always fits**, because the column refuses one longer than    /// [`HOLD_REASON_MAX`] and a refused write would leave the queue with no    /// reason at all — which is the one outcome this whole module exists to    /// prevent. Three shapes, in the order they are tried:    ///    ///   1. every Mac said the SAME thing → say it once, naming them where the    ///      names are what make it readable;    ///   2. otherwise, each Mac and its own reason, joined;    ///   3. and if that will not fit, as many as do, plus the count of the    ///      rest — never a sentence cut off mid-word.    #[must_use]    pub fn hold_reason(&self, lines: &[LineRow]) -> String {        let sentence = self.sentence(lines);        if sentence.chars().count() <= HOLD_REASON_MAX {            return sentence;        }        let Refusal::EveryDeviceBusy(refused) = self else {            // Unreachable in practice — `NoDevices` is one short sentence —            // and a truncation here would be the silent fallback this repo            // does not allow, so it says what it is instead.            return say(lines, "none_can", &[]);        };        let mut kept: Vec<String> = Vec::new();        for one in refused {            let clause = one.sentence(lines);            let would_be = clauses(lines, &kept, Some(&clause), refused.len() - kept.len() - 1);            if would_be.chars().count() > HOLD_REASON_MAX {                break;            }            kept.push(clause);        }        if kept.is_empty() {            return say(lines, "each_its_own", &[("count", &refused.len().to_string())]);        }        clauses(lines, &kept, None, refused.len() - kept.len())    }    /// The whole sentence, however long it comes out — what a log line says and    /// what [`Refusal::hold_reason`] shortens when it has to.    #[must_use]    pub fn sentence(&self, lines: &[LineRow]) -> String {        match self {            Refusal::NoDevices => say(lines, "no_devices", &[]),            Refusal::NoOwnDatabase => say(lines, "no_own_database", &[]),            Refusal::EveryDeviceBusy(refused) => {                if let Some(first) = refused.first() {                    if refused.iter().all(|one| one.why.same_as(&first.why)) {                        let names: Vec<String> =                            refused.iter().map(|one| one.name.clone()).collect();                        return first.why.household_sentence(lines, &listed(lines, &names), refused.len());                    }                }                let reasons: Vec<String> = refused.iter().map(|one| one.sentence(lines)).collect();                clauses(lines, &reasons, None, 0)            }        }    }}/// The per-Mac sentences, joined, with `and N more` when some were left out.fn clauses(lines: &[LineRow], kept: &[String], extra: Option<&str>, more: usize) -> String {    let mut all: Vec<&str> = kept.iter().map(String::as_str).collect();    if let Some(extra) = extra {        all.push(extra);    }    let body = all.join(&say(lines, "between", &[]));    if more == 0 {        say(lines, "waiting", &[("body", &body)])    } else {        say(lines, "waiting_more", &[("body", &body), ("more", &more.to_string())])    }}/// WHICH DATABASE'S DEVICE ROWS a session's candidate Macs are read from:/// MINE's — the Mac owner's own database — BY ID, whichever database queued/// the session.////// The Macs that host sessions are the owner's machines, and they are devices/// of the owner's own database; another database a Mac also serves lists its/// own devices, and a Mac placed off THAT list would be a stranger's machine/// or none. So the answer is `mine` and never `session_database` unless the two/// are the same — and with no Mine recorded it is the named refusal/// [`Refusal::NoOwnDatabase`], never a fallback to that database's own rows.////// `mine` comes from the server's registry (`Registry::mine`; P1's/// `kind = 'personal'` later), never from the order its rows are listed in.pub fn machines_database<'a>(    mine: Option<&'a str>,    _session_database: &'a str,) -> Result<&'a str, Refusal> {    mine.ok_or(Refusal::NoOwnDatabase)}/// Pick the Mac this session goes to, or say why none can take it.////// **A device that cannot host is not a candidate at all**/// ([`super::machines::can_host`]): a revoked device, or a phone that has/// never reported, is left out before anything is checked, so it is never/// placed on and never named in the sentence a held card reads. With no/// device left the answer is [`Refusal::NoDevices`].////// A Mac has to pass every one of these://////   - it reported within [`SEEN_WINDOW_MINUTES`]///     ([`super::machines::report_state_at`]);///   - `sessions_running < sessions_cap`;///   - `mem_free_pct >= `[`MIN_FREE_MEMORY_PCT`];///   - what `ask` costs fits in what is left of its budget///     ([`super::budget`]) — the check the build lock used to stand in for;///   - the session's tool is installed on it;///   - it is signed in for that tool, and that login is under///     [`ACCOUNT_LIMIT_PCT`];///   - when the session names a repository and the Mac has said which ones it///     holds, that repository is one of them.////// `repo` is the session's repository as it was written on the row, or `None`/// for a session that names none.////// **The freest Mac wins, and free means `load1`.** It is the one number that/// answers "is that Mac busy right now", and it is what the strip on the/// devices page draws. The tie-break behind it is most free memory, then/// fewest sessions running, then the device key — the key last so the answer is/// TOTAL: two Macs with identical readings must not depend on the order the/// rows came back in, or the worker and the phone can show different picks from/// the same file. A Mac that reported no load sorts BEHIND every Mac that did,/// because a load nobody knows is not a Mac anybody can call free.pub fn pick_device(    candidates: &[DeviceFacts],    tool: &str,    repo: Option<&str>,    ask: &Ask,    now: DateTime<Utc>,) -> Result<String, Refusal> {    let candidates: Vec<&DeviceFacts> = candidates.iter().filter(|device| hosts(device)).collect();    if candidates.is_empty() {        return Err(Refusal::NoDevices);    }    // Canonicalised ONCE, by the function the Macs reported through. A    // repository that will not canonicalise is one no Mac can be compared    // against, and it is not a reason to refuse them all.    let repo = repo.and_then(super::repo_ref::canonical_repo_url);    let mut free: Vec<&DeviceFacts> = Vec::new();    let mut refused: Vec<RefusedDevice> = Vec::new();    for device in candidates {        match refuse(device, tool, repo.as_deref(), ask, now) {            None => free.push(device),            Some(why) => refused.push(RefusedDevice {                device_id: device.device_id.clone(),                name: device.name.clone(),                why,            }),        }    }    let Some(best) = free.into_iter().min_by(|left, right| {        busyness(left)            .total_cmp(&busyness(right))            .then(                right                    .mem_free_pct                    .unwrap_or(0)                    .cmp(&left.mem_free_pct.unwrap_or(0)),            )            .then(left.sessions_running.cmp(&right.sessions_running))            .then(left.device_id.cmp(&right.device_id))    }) else {        refused.sort_by(|left, right| left.name.cmp(&right.name));        return Err(Refusal::EveryDeviceBusy(refused));    };    Ok(best.device_id.clone())}/// [`super::machines::can_host`] over the facts the worker read.fn hosts(device: &DeviceFacts) -> bool {    let sampled_at = device        .sampled_at        .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true));    can_host(        device.platform.as_deref(),        sampled_at.as_deref(),        device.host_version.as_deref(),        device.revoked.then_some("revoked"),    )}/// `load1`, with an unreported one sorting behind every reported one.////// `f64::INFINITY` rather than a large number: it is the value that is greater/// than every load a Mac can report, including one that has genuinely gone/// vertical, and it is exact.fn busyness(device: &DeviceFacts) -> f64 {    device.load1.unwrap_or(f64::INFINITY)}/// The per-Mac half: the first check this one fails, or `None`.fn refuse(    device: &DeviceFacts,    tool: &str,    repo: Option<&str>,    ask: &Ask,    now: DateTime<Utc>,) -> Option<DeviceRefusal> {    // `pick_device` has already left a revoked device out (it cannot host);    // this stays so the per-device half never admits one on its own.    if device.revoked {        return Some(DeviceRefusal::Revoked);    }    // THE ONE REPORT RULE (`machines::report_state_at`): the window the    // phone draws "has not reported since" from is the window this refuses on.    match (report_state_at(device.sampled_at, now), device.sampled_at) {        (ReportState::Current, _) => {}        (ReportState::Silent { .. }, Some(sampled_at)) => {            return Some(DeviceRefusal::NotSeenRecently {                minutes: (now - sampled_at).num_minutes(),            });        }        (ReportState::Silent { .. }, None) => return Some(DeviceRefusal::NeverReported),    }    if device.sessions_running >= device.sessions_cap {        return Some(DeviceRefusal::AtCap {            running: device.sessions_running,            cap: device.sessions_cap,        });    }    let Some(mem_free_pct) = device.mem_free_pct else {        return Some(DeviceRefusal::MemoryUnknown);    };    if mem_free_pct < MIN_FREE_MEMORY_PCT {        return Some(DeviceRefusal::LowMemory {            free_pct: mem_free_pct,        });    }    // THE BUDGET, AND THE BUILD LOCK INSIDE IT. A Mac used to be refused    // outright while `/tmp/tinmen-build.lock` was held, which turned a 48 GB    // machine away from a 0.6 GB agent because somebody was compiling. What    // the build is really costing is measured and sits in `mem_committed_gb`;    // what is left is arithmetic.    //    // A Mac that has reported NEITHER number is one whose helper is too old to    // measure. It is not refused — the checks above still cover it — and this    // is the one place in the module where a missing reading is not a no, so    // it is written down rather than left to be inferred.    if let (Some(budget), Some(committed)) = (device.mem_budget_gb, device.mem_committed_gb) {        let free = free_gb(budget, committed);        let cost = ask.mem_gb(device.session_peak);        if !admits(free, cost) {            return Some(DeviceRefusal::NoRoom {                // As the SENTENCE says them — see `budget::free_as_said`.                // The variant carries the printed numbers rather than the raw                // ones so that what a test asserts and what a person reads on                // the card are the same two figures.                free_gb: free_as_said(free),                job: ask.label(),                cost_gb: cost_as_said(cost),            });        }    }    // THE DISK, with the memory: a lane leaves a worktree, a target and build    // data behind it, and a Mac it would take under its reserve is a Mac whose    // next build fails (storage note c7d20613). Unreported is not a no.    if let (Some(free), Some(total)) = (device.disk_free_gb, device.disk_total_gb) {        let reserve = super::budget::disk_reserve_gb(total, device.keep_free_bytes);        if free - LANE_DISK_GB < reserve {            return Some(DeviceRefusal::LowDisk { free_gb: free.floor(), reserve_gb: reserve });        }    }    if !device.agents.iter().any(|agent| agent == tool) {        return Some(DeviceRefusal::ToolNotInstalled {            tool: tool.to_string(),        });    }    let Some(account) = &device.account else {        return Some(DeviceRefusal::NotSignedIn {            tool: tool.to_string(),        });    };    // No reading yet is not a refusal: 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.    if let Some(pct) = account.five_hour_pct {        if pct >= ACCOUNT_LIMIT_PCT {            return Some(DeviceRefusal::AccountNearLimit {                account: account.email.clone(),                pct,            });        }    }    // THE CODE, LAST: every check above is about the Mac, and this one is    // about the session — so the sentence a person reads for a Mac that is    // also full, or signed out, is the one they can do something about from    // that Mac. A Mac that has not said what it holds is not refused.    if let (Some(repo), Some(held)) = (repo, device.repos.as_ref()) {        if !held.iter().any(|one| one == repo) {            return Some(DeviceRefusal::RepoNotHere {                repo: repo.rsplit('/').next().unwrap_or(repo).to_string(),            });        }    }    None}/// The sentence a QUEUED session wears when it was placed on a Mac and that/// Mac has not picked it up.////// Not a [`Refusal`]: nothing refused anything. The owner named a Mac, the row/// is sitting on it, and the only honest thing to say is that the Mac has not/// answered — which is a question about whether CottonDB is running there, and/// is the one the person can actually act on.#[must_use]pub fn unclaimed_reason(lines: &[LineRow], machine: &str) -> String {    say(lines, "unclaimed", &[("machine", machine)])}/// What a held card calls a Mac it has no name for.#[must_use]pub fn unnamed_mac(lines: &[LineRow]) -> String {    say(lines, "that_mac", &[])}/// How long a Mac has to claim a session placed on it before the card says so.////// **Ten minutes**, the same window a Mac has to have reported in: a Mac that/// is awake claims in seconds (its client is woken by the same fold that/// carried the row), and one that has not claimed in ten minutes is one that is/// not listening.pub const CLAIM_WINDOW_MINUTES: i64 = 10;#[cfg(test)]#[path = "dispatch_tests.rs"]mod tests;