Cotton code
946 lines · 36.3 KB · RustRaw
//! What this Mac looks like right now — the five-minute sample.//!//! The dispatcher on the serving Mac picks a device from these numbers (design://! seen recently, not paused, under its session cap, memory free, no build//! lock, the tool installed), so every one of them is a REFUSAL somebody can//! read. That is why the map of installed agents leaves an absent agent OUT//! rather than recording an empty version: "not installed" and "installed,//! version unknown" are different answers and the dispatcher acts differently//! on them.//!//! THE READING IS SPLIT FROM THE PARSING, deliberately. Every number this//! machine reports comes from a text or a syscall that differs between macOS//! and the Linux the `rust` job runs on; the parsers are pure functions with//! their own tests, and the platform readers below them are four lines each.use std::collections::BTreeMap;use std::path::Path;use crate::binary::SelfReport;use crate::clock::Clock;use crate::protocol::{MachineSample, SignedIn, Tool};/// The build mutex every heavy build on a Tinmen Mac queues behind.////// It is a DIRECTORY with a `pid` file inside it (`scripts/with-build-lock.sh`),/// not a lock file — so "held" means the pid in it is a process that still/// exists, and a crashed holder reads as not held, exactly as the script's own/// reclaim rule does.pub const BUILD_LOCK_DIR: &str = "/tmp/tinmen-build.lock";/// Linux's memory interface.////// A KERNEL PSEUDO-FILE, not a file in any lane of this repository — declared/// as a constant beside [`BUILD_LOCK_DIR`] for the same reason, which is that/// an operating system's path is named once and never spelled inline. The only/// build that reads it is the Linux one, which is what the `rust` job runs.#[cfg(not(target_os = "macos"))]pub const PROC_MEMINFO: &str = "/proc/meminfo";/// Linux's CPU interface — the same kind of kernel pseudo-file as/// [`PROC_MEMINFO`], named once for the same reason.#[cfg(not(target_os = "macos"))]pub const PROC_CPUINFO: &str = "/proc/cpuinfo";/// Where a Linux names its release. Not a kernel file but the distribution's,/// and still the operating system's path rather than this repository's.#[cfg(not(target_os = "macos"))]pub const ETC_OS_RELEASE: &str = "/etc/os-release";/// How often `serve` samples itself — and so how often this machine REPORTS:/// every sample rewrites the device row the dispatcher and the phone read.////// **Five minutes**, `cotton_core::rules::machines::REPORT_INTERVAL_MINUTES`./// This crate does not depend on `cotton-core`, so the number is written here/// and `machine_tests.rs` reads the core's declaration by path and fails when/// the two differ: a report slower than the core's seen window allows for/// would make a healthy Mac read as silent. The thirty-day history keeps its/// own fifteen-minute cadence (`cotton_core::rules::samples`) — the mirror/// only adds a history point when that one is due.pub const SAMPLE_EVERY_SECONDS: u64 = 5 * 60;/// Bytes in a gigabyte, as every number here reports them.const GIB: f64 = 1024.0 * 1024.0 * 1024.0;/// What the CALLER measured about what is running on this Mac.////// Handed in for the same reason `binary` is: the caller walks the process/// table ([`crate::processes`]) because it is the only thing that knows which/// pids are its own sessions, and `sample` stays a function a test can call/// with numbers it invented.#[derive(Debug, Clone, Copy, Default, PartialEq)]pub struct Measured {    /// **ONE READING OF MEMORY, taken by the caller** ([`memory`]).    ///    /// It is here rather than read inside `sample` because the committed    /// figure is computed FROM it: the free percentage on the sample and the    /// memory the sample says is promised have to be two spellings of one    /// instant, and two `vm_stat` calls a few milliseconds apart are two    /// instants.    pub memory: Memory,    /// Memory already promised, gigabytes —    /// [`crate::processes::committed_gb`].    pub committed_gb: f64,    /// The largest one session's tree has been measured at, gigabytes.    pub session_peak_gb: Option<f64>,    /// How many readings that peak is drawn from.    pub session_peak_samples: u32,}/// WHAT THIS MACHINE IS — read once, at `serve` start.////// The sample above says how a Mac is DOING every five minutes; this says/// what it is, and it is handed into [`sample`] the way `binary` is rather/// than re-read on the tick. Two reasons. A constant re-read every five/// minutes is a reading by another name — the store keeps these three OUT of/// the presence columns and the mirror writes them in their own op, once, and/// only when one changes, so the daemon reading them once is the same fact/// told the same way at every hop. And the two that can change under a running/// daemon — the OS version on an update, the volume on a drive swap — are/// exactly the events that restart it.////// Every field is `None` when the machine would not say, never an empty/// string or a zero: `None` is "has not said" on the wire and NULL in the file.#[derive(Debug, Clone, Default, PartialEq)]pub struct Facts {    /// The chip's marketing name — `Apple M4 Pro` on a Mac, the first    /// `model name` of `/proc/cpuinfo` on the Linux the `rust` job runs on.    pub chip: Option<String>,    /// The operating system's version — `26.0.1` on a Mac, `PRETTY_NAME` from    /// `/etc/os-release` on Linux.    pub os_version: Option<String>,    /// The size of the volume the data directory is on, gigabytes.    pub disk_total_gb: Option<f64>,}/// Read what this machine is.pub fn facts(data_dir: &Path) -> Facts {    Facts {        chip: chip(),        os_version: os_version(),        disk_total_gb: disk_gb(data_dir).map(|(_, total)| total),    }}/// WHAT A SAMPLE IS HANDED rather than reads: the three answers that were/// decided somewhere else, at some other time, and must not be re-answered/// from whatever is on disk this minute.//////   * `binary` — what this host has decided about its OWN executable///     ([`crate::binary::Watch::report`]), recorded once at `serve` start.///   * `measured` — the memory and the sessions' peaks ([`Measured`]), read by///     the tick that owns the process tree.///   * `facts` — what the machine IS ([`Facts`]), read once and not a reading.////// One struct rather than three parameters so the signature says which/// arguments are readings and which are hand-me-downs — and so a fourth of/// the kind lands here, not as a ninth argument.#[derive(Debug, Clone, PartialEq)]pub struct HandedIn<'a> {    pub binary: SelfReport,    pub measured: Measured,    pub facts: &'a Facts,}/// Read this machine.////// The live readings — the load, the free disk, the CPU count, the build/// lock — are taken here and now; everything in `handed` was decided/// elsewhere ([`HandedIn`] says where) and is carried, never re-read.pub fn sample(    clock: &dyn Clock,    data_dir: &Path,    sessions_running: u32,    agents: BTreeMap<String, String>,    accounts: BTreeMap<String, SignedIn>,    handed: HandedIn<'_>,) -> MachineSample {    let HandedIn {        binary,        measured,        facts,    } = handed;    MachineSample {        hardware_id: crate::hardware::hardware_id(),        sampled_at: clock.now_rfc3339(),        load1: load1(),        mem_free_pct: measured.memory.free_pct,        mem_total_gb: measured.memory.total_gb,        disk_free_gb: free_disk_gb(data_dir),        cpu_count: cpu_count(),        chip: facts.chip.clone(),        os_version: facts.os_version.clone(),        // Retry the volume reading on every sample: a missed startup probe        // must not leave every newly served file without capacity forever.        disk_total_gb: facts.disk_total_gb.or_else(|| disk_gb(data_dir).map(|(_, total)| total)),        sessions_running,        build_lock_held: build_lock_held(Path::new(BUILD_LOCK_DIR)),        mem_committed_gb: measured.committed_gb,        session_peak_gb: measured.session_peak_gb,        session_peak_samples: measured.session_peak_samples,        agents,        accounts,        host_version: crate::HOST_VERSION.to_string(),        binary_fingerprint: binary.fingerprint,        update_pending: binary.update_pending,    }}/// What asking one agent for its version answered.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Found {    /// The binary that answered — an absolute path when the login environment    /// resolved one.    pub path: String,    /// What it printed.    pub said: String,}/// The agents on this machine, and where they were found.////// The sample carries `versions` alone (`PROTOCOL.md`, *Sampling*); `found_at`/// is for the log, because "not installed" on a Mac where the person can run/// `claude` by hand is always a question about WHICH `claude` this host looked/// for and on what PATH.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Detected {    /// `claude-code` / `codex` / [`EXTRA_PROGRAMS`] to a version.    pub versions: BTreeMap<String, String>,    /// The same keys, to the binary that answered.    pub found_at: BTreeMap<String, String>,}/// The programs in this map that are NOT coding agents.////// **`npm` is here because the Code 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, and the panel says *Codex needs/// Node.js* instead of offering it. It is looked for exactly as an agent is —/// on the PERSON'S path, on every sample — because a `node` installed through/// `nvm` is on no path this process would otherwise see.////// Cotton never installs Node itself: that is a choice about somebody's/// machine that belongs to them, and the sentence names nodejs.org.pub const EXTRA_PROGRAMS: [&str; 1] = ["npm"];/// What the agents on this machine report when asked their version.////// An agent that is not on the PATH, or that answers nothing a version can be/// read out of, is ABSENT from the map.////// The map also carries [`EXTRA_PROGRAMS`] under their own names, which is why/// the field is read by KEY at every end rather than iterated: a reader that/// listed whatever was in it would draw `npm` as a coding agent.pub fn installed_agents(ask: impl Fn(&str) -> Option<Found>) -> Detected {    let mut detected = Detected::default();    let agents = [Tool::Claude, Tool::Codex]        .into_iter()        .map(|tool| {            (                match tool {                    Tool::Claude => "claude",                    Tool::Codex => "codex",                },                tool.agent_key(),            )        })        .chain(EXTRA_PROGRAMS.into_iter().map(|program| (program, program)));    for (program, key) in agents {        let Some(found) = ask(program) else { continue };        let Some(version) = parse_version(&found.said) else {            continue;        };        detected.versions.insert(key.to_string(), version);        detected.found_at.insert(key.to_string(), found.path);    }    detected}/// Ask each agent its version, resolved and run against `env`.////// THE WHOLE POINT OF THE LOGIN CAPTURE. Under launchd this process's own PATH/// is `/usr/bin:/bin:/usr/sbin:/sbin` and neither agent is on it, so a lookup/// against the process would answer "no agent on this Mac" on a machine where/// the person runs `claude` every day. The binary is resolved against the/// captured PATH and run in the captured environment — the same one a session/// will run in, so a detection that succeeds is a launch that can.pub fn detect(env: &crate::login_env::LoginEnv) -> Detected {    let detected = installed_agents(|program| {        let path = env.program_path(program);        let mut command = std::process::Command::new(&path);        command.arg("--version");        for (name, value) in env.vars() {            command.env(name, value);        }        output_within(command, ACCOUNT_ASK_TIMEOUT)            .filter(|out| out.status.success())            .map(|out| Found {                path,                said: String::from_utf8_lossy(&out.stdout).to_string(),            })    });    with_signing_identity(detected, ask_keychain().team())}/// The key under which the map says this Mac holds a valid Developer ID/// Application identity. The core's runner rules that read it were retired/// with the runner tables (TABLE DROP 1); the key stays as it was sampled.pub const SIGNING_IDENTITY_KEY: &str = "developer-id";/// The program the release lane asks, spelled once.////// `/usr/bin/security` and not `security` on a `PATH`: a relative name would/// be a different program on a Mac with a shadowing one.pub const SECURITY_PROGRAM: &str = "/usr/bin/security";/// The arguments, in the release lane's own order.////// `-v` is load-bearing: without it the listing includes EXPIRED and revoked/// identities, and a Mac whose certificate ran out last year would say it can/// sign and fail every release placed on it until somebody looked.pub const FIND_IDENTITY_ARGS: [&str; 4] = ["find-identity", "-v", "-p", "codesigning"];/// What a line has to say for this Mac to be able to sign a release — the/// same line the release-signing installer decides by.pub const SIGNING_IDENTITY_MARKER: &str = "Developer ID Application:";/// The team of the first valid Developer ID Application identity in a/// `security find-identity -v` listing, or `None` when it names none.////// Pure, over the bytes `security` printed. An empty listing, an error message/// and a listing of other kinds of identity are all `None`. A line reads/// `1) <hash> "Developer ID Application: Name (TEAM)"`; an identity whose name/// carries no team in brackets is still an identity, and answers its name.#[must_use]pub fn signing_identity(listing: &str) -> Option<String> {    let line = listing        .lines()        .find(|line| line.contains(SIGNING_IDENTITY_MARKER))?;    let name = line        .split_once(SIGNING_IDENTITY_MARKER)        .map_or("", |(_, name)| name)        .trim()        .trim_end_matches('"')        .trim();    let team = name        .rsplit_once('(')        .and_then(|(_, rest)| rest.split_once(')'))        .map(|(team, _)| team.trim())        .filter(|team| !team.is_empty());    Some(team.unwrap_or(name).to_string())}/// What a Mac's keychain said when asked whether it can sign a release.////// THREE answers, because two things are decided from it and they must not be/// decided from a silence: this Mac's runner row ADOPTS the signing label on/// [`Keychain::Signs`] and DROPS it on [`Keychain::CannotSign`], and on/// [`Keychain::DidNotSay`] it changes nothing — a call that failed is not a/// Mac that lost its certificate, and dropping the label on it would take a/// working builder off the release lanes.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Keychain {    /// It lists a valid Developer ID Application identity, of this team.    Signs(String),    /// It answered, and lists none.    CannotSign,    /// It was not asked or did not answer: not a Mac, the program missing,    /// the call failed, or a reply with no count of identities in it.    DidNotSay,}impl Keychain {    /// The identity's team, when it holds one.    #[must_use]    pub fn team(&self) -> Option<String> {        match self {            Keychain::Signs(team) => Some(team.clone()),            Keychain::CannotSign | Keychain::DidNotSay => None,        }    }    /// Can this Mac sign — `None` when the keychain did not say.    #[must_use]    pub fn can_sign(&self) -> Option<bool> {        match self {            Keychain::Signs(_) => Some(true),            Keychain::CannotSign => Some(false),            Keychain::DidNotSay => None,        }    }}/// How `security find-identity` ends every listing it completed — "3 valid/// identities found", "0 valid identities found". A reply without it is an/// error message, not an answer.pub const IDENTITIES_COUNTED: &str = "valid identities found";/// The keychain's answer, out of what `security find-identity -v` printed.////// Pure. An identity is a yes; a completed listing without one is a no; and/// anything else — nothing at all, an error with no count — did not say.#[must_use]pub fn keychain_said(listing: &str) -> Keychain {    match signing_identity(listing) {        Some(team) => Keychain::Signs(team),        None if listing            .lines()            .any(|line| line.trim_end().ends_with(IDENTITIES_COUNTED)) =>        {            Keychain::CannotSign        }        None => Keychain::DidNotSay,    }}/// Ask this Mac's keychain for a valid Developer ID Application identity —/// the release lane's own question.////// Asked with NOTHING of this process's environment — a stray `HOME` would/// point the lookup at another login's keychain. BLOCKING: one short child/// process.#[must_use]pub fn ask_keychain() -> Keychain {    if !cfg!(target_os = "macos") || !Path::new(SECURITY_PROGRAM).exists() {        return Keychain::DidNotSay;    }    let mut command = std::process::Command::new(SECURITY_PROGRAM);    command.args(FIND_IDENTITY_ARGS).env_clear();    match output_within(command, ACCOUNT_ASK_TIMEOUT) {        Some(reply) if reply.status.success() => {            keychain_said(&String::from_utf8_lossy(&reply.stdout))        }        _ => Keychain::DidNotSay,    }}/// The map with this Mac's signing identity beside the programs, when it/// holds one — under [`SIGNING_IDENTITY_KEY`], to the identity's team, found/// at the program that was asked.////// **A MAC THAT CAN SIGN SAYS SO ON ITS OWN SAMPLE.** Every Mac may be a/// builder (owner, 12 Oct 2026), so which of them can actually sign a release/// is a fact a scheduler reads per machine, and only the machine can ask its/// own keychain. A Mac with no identity leaves the key OUT, for the agents'/// own reason: absent is "cannot sign", and there is no empty value to/// misread. Like `npm`, it is read by KEY and is no coding agent.#[must_use]pub fn with_signing_identity(mut detected: Detected, identity: Option<String>) -> Detected {    if let Some(team) = identity {        detected            .versions            .insert(SIGNING_IDENTITY_KEY.to_string(), team);        detected.found_at.insert(            SIGNING_IDENTITY_KEY.to_string(),            SECURITY_PROGRAM.to_string(),        );    }    detected}/// How long an agent is given to say who is signed in.////// Ten seconds. `claude auth status` answers in well under one; the bound is/// for the day it does not, because this runs on the tick that publishes the/// sample, and a sample that never leaves reads to the dispatcher as a Mac/// that went away.pub const ACCOUNT_ASK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);/// Who each DETECTED agent is signed in as.////// `ask` is handed the agent's key and the arguments its adapter names, and/// answers what the agent printed — or nothing, for an agent that did not/// answer. An agent that was not detected is not asked: there is no binary to/// ask, and "not installed" is already the answer about it.pub fn signed_in_agents(    detected: &Detected,    ask: impl Fn(&str, &[&str]) -> Option<String>,) -> BTreeMap<String, SignedIn> {    let mut accounts = BTreeMap::new();    for tool in [Tool::Claude, Tool::Codex] {        let key = tool.agent_key();        if !detected.versions.contains_key(key) {            continue;        }        let adapter = crate::agents::adapter(tool);        let Some(argv) = adapter.account_argv() else {            continue;        };        let Some(said) = ask(key, argv) else { continue };        if let Some(account) = adapter.read_account(&said) {            accounts.insert(key.to_string(), account);        }    }    accounts}/// Ask each detected agent who is signed in, in the login environment —/// [`detect`]'s rule, for [`detect`]'s reason, and against the binary/// [`detect`] found.pub fn signed_in(    env: &crate::login_env::LoginEnv,    detected: &Detected,) -> BTreeMap<String, SignedIn> {    signed_in_agents(detected, |key, argv| {        let path = detected.found_at.get(key)?;        let mut command = std::process::Command::new(path);        command            .args(argv)            .stdin(std::process::Stdio::null())            .stdout(std::process::Stdio::piped())            .stderr(std::process::Stdio::null());        for (name, value) in env.vars() {            command.env(name, value);        }        said_within(command, ACCOUNT_ASK_TIMEOUT)    })}/// What a command printed, if it finished in time. The exit code is NOT read:/// `claude auth status` exits 1 for "signed out" and still prints the answer.fn said_within(command: std::process::Command, within: std::time::Duration) -> Option<String> {    output_within(command, within)        .map(|output| String::from_utf8_lossy(&output.stdout).into_owned())}/// Bound the process AND its output pipe. A descendant can keep stdout open/// after the immediate child exits; waiting for EOF must share the deadline.pub(crate) fn output_within(    mut command: std::process::Command,    within: std::time::Duration,) -> Option<std::process::Output> {    use std::io::{Read as _, Write as _};    use std::os::fd::AsRawFd as _;    use std::os::unix::process::CommandExt as _;    let program = command.get_program().to_string_lossy().into_owned();    command        .stdin(std::process::Stdio::null())        .stdout(std::process::Stdio::piped())        .stderr(std::process::Stdio::null())        .process_group(0);    let mut child = command.spawn().ok()?;    let mut stdout = child.stdout.take()?;    // SAFETY: stdout owns this live fd. Nonblocking reads let process and pipe    // completion share one deadline without leaving an unbounded reader thread.    let flags = unsafe { libc::fcntl(stdout.as_raw_fd(), libc::F_GETFL) };    if flags < 0        || unsafe { libc::fcntl(stdout.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0    {        let _ = child.kill();        let _ = child.wait();        return None;    }    let deadline = std::time::Instant::now() + within;    let mut bytes = Vec::new();    let mut eof = false;    loop {        let mut buffer = [0; 8192];        match stdout.read(&mut buffer) {            Ok(0) => eof = true,            Ok(count) => bytes.extend_from_slice(&buffer[..count]),            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}            Err(_) => break,        }        match child.try_wait() {            Ok(Some(status)) if eof => {                return Some(std::process::Output {                    status,                    stdout: bytes,                    stderr: Vec::new(),                })            }            Err(_) => break,            _ => {}        }        if std::time::Instant::now() >= deadline || bytes.len() > 1_048_576 {            // Logging must not panic when disk-full makes the host log unwritable.            let _ = writeln!(std::io::stderr(), "cotton-session-host: sample probe {program} did not finish within its output/time budget");            break;        }        std::thread::sleep(std::time::Duration::from_millis(5));    }    // SAFETY: this exact group was created for our child above. No unrelated    // process or session is signalled, including descendants holding its pipe.    unsafe {        libc::kill(-(child.id() as i32), libc::SIGKILL);    }    let _ = child.kill();    let _ = child.wait();    None}/// One line saying what was found and where — for the host's log.pub fn describe(detected: &Detected) -> String {    if detected.versions.is_empty() {        return "no coding agent answered on this host's PATH".to_string();    }    detected        .versions        .iter()        .map(|(agent, version)| {            let at = detected                .found_at                .get(agent)                .map(String::as_str)                .unwrap_or(agent);            format!("{agent} {version} at {at}")        })        .collect::<Vec<_>>()        .join(", ")}/// The version inside whatever `--version` printed.////// `claude --version` answers `2.1.274 (Claude Code)`; `codex --version`/// answers `codex-cli 0.55.0`. Both are "the first thing on the first line/// that looks like a version", and anything else is no answer at all rather/// than a zero.pub fn parse_version(said: &str) -> Option<String> {    said.lines().next()?.split_whitespace().find_map(|word| {        let trimmed = word.trim_matches(|c: char| !c.is_ascii_alphanumeric());        // `v1.2.3` is the same version as `1.2.3`; the `v` is a convention,        // not part of the number, and the map's value is compared with one a        // person typed.        let trimmed = match trimmed.strip_prefix(['v', 'V']) {            Some(rest) if rest.starts_with(|c: char| c.is_ascii_digit()) => rest,            _ => trimmed,        };        let mut parts = trimmed.split('.');        let looks_like = parts.clone().count() >= 2            && parts.all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()));        looks_like.then(|| trimmed.to_string())    })}/// Is the machine-wide build mutex held by a process that still exists?pub fn build_lock_held(lock_dir: &Path) -> bool {    build_lock_pid(lock_dir).is_some()}/// WHICH process holds the machine-wide build mutex, while one does.////// The bool was enough while the lock was a throttle. It is not enough now/// that the lock is measured: the budget wants the holder's whole process/// tree, and only a pid names it ([`crate::processes::committed_gb`]).pub fn build_lock_pid(lock_dir: &Path) -> Option<u32> {    let text = std::fs::read_to_string(lock_dir.join("pid")).ok()?;    let pid = parse_pid(&text)?;    crate::pty::alive(pid).then_some(pid)}/// The pid inside the lock's `pid` file.pub fn parse_pid(text: &str) -> Option<u32> {    let trimmed = text.trim();    (!trimmed.is_empty()).then(|| trimmed.parse().ok()).flatten()}/// Total and free memory.#[derive(Debug, Clone, Copy, Default, PartialEq)]pub struct Memory {    /// Gigabytes.    pub total_gb: f64,    /// 0–100.    pub free_pct: u8,}impl Memory {    /// **WHAT THIS MAC IS ACTUALLY USING**, gigabytes.    ///    /// The kernel's own answer, shared pages and all, which is why the budget    /// starts here instead of summing a process table    /// ([`crate::processes::committed_gb`]).    pub fn used_gb(&self) -> f64 {        self.total_gb * (100u8.saturating_sub(self.free_pct) as f64) / 100.0    }}/// `MemTotal` and `MemAvailable` out of `/proc/meminfo`, in kilobytes.////// Linux's own answer to "how much memory could a new process have": the/// kernel computes `MemAvailable` including reclaimable cache, which free +/// buffers arithmetic gets wrong on a box that has been up for a week.pub fn parse_meminfo(text: &str) -> Option<(u64, u64)> {    let field = |name: &str| -> Option<u64> {        text.lines()            .find(|line| line.starts_with(name))?            .split_whitespace()            .nth(1)?            .parse()            .ok()    };    Some((field("MemTotal:")?, field("MemAvailable:")?))}/// Free pages out of `vm_stat`'s output, macOS's answer.////// Free plus INACTIVE plus SPECULATIVE: an inactive page is memory the kernel/// will hand over the moment somebody asks, and counting only `Pages free` on/// a Mac that has been awake for a day reports about 2% free while Activity/// Monitor shows half the machine idle — a number the dispatcher would refuse/// every launch on.pub fn parse_vm_stat_free_pages(text: &str) -> Option<u64> {    let field = |name: &str| -> Option<u64> {        let line = text.lines().find(|line| line.starts_with(name))?;        line.split(':')            .nth(1)?            .trim()            .trim_end_matches('.')            .parse()            .ok()    };    let free = field("Pages free")?;    let inactive = field("Pages inactive").unwrap_or(0);    let speculative = field("Pages speculative").unwrap_or(0);    Some(free + inactive + speculative)}/// Free memory as a whole percent, 0–100.pub fn free_pct(free: u64, total: u64) -> u8 {    if total == 0 {        return 0;    }    let pct = (free as f64 / total as f64 * 100.0).round();    pct.clamp(0.0, 100.0) as u8}/// The one-minute load average.pub fn load1() -> f64 {    let mut averages = [0f64; 3];    // SAFETY: `getloadavg(3)` writes at most `nelem` doubles into the array we    // hand it, and we hand it its own length.    let taken = unsafe { libc::getloadavg(averages.as_mut_ptr(), 3) };    if taken < 1 {        return 0.0;    }    averages[0]}/// Logical CPUs.pub fn cpu_count() -> u32 {    std::thread::available_parallelism()        .map(|count| count.get() as u32)        .unwrap_or(1)}/// Free space on the volume that holds `path`, in gigabytes.////// Zero for a path that is not there: the sample's number is `f64`, and the/// reading has said zero for a missing volume since its first release.pub fn free_disk_gb(path: &Path) -> f64 {    disk_gb(path).map_or(0.0, |(free, _)| free)}/// The volume that holds `path`: `(free, total)` gigabytes from ONE `statvfs`,/// or `None` for a path that is not there. One syscall, two numbers, so the/// free space and the size it is free out of are two spellings of one instant.pub fn disk_gb(path: &Path) -> Option<(f64, f64)> {    let c_path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).ok()?;    let mut stats: libc::statvfs = unsafe { std::mem::zeroed() };    // SAFETY: `statvfs(3)` fills the struct we own, from a NUL-terminated path    // we own. A path that does not exist answers -1 and leaves the struct as    // we zeroed it.    let answered = unsafe { libc::statvfs(c_path.as_ptr(), &mut stats) };    if answered != 0 {        return None;    }    let block = if stats.f_frsize > 0 {        stats.f_frsize as f64    } else {        stats.f_bsize as f64    };    Some((        (stats.f_bavail as f64 * block) / GIB,        (stats.f_blocks as f64 * block) / GIB,    ))}/// The chip's name — `machdep.cpu.brand_string`, which on Apple silicon is/// the marketing name (`Apple M4 Pro`).#[cfg(target_os = "macos")]pub fn chip() -> Option<String> {    sysctl_string(c"machdep.cpu.brand_string")}/// The operating system's version — `kern.osproductversion`, the same string/// `sw_vers -productVersion` prints, without a subprocess.#[cfg(target_os = "macos")]pub fn os_version() -> Option<String> {    sysctl_string(c"kern.osproductversion")}/// A string-valued `sysctl`, in the two-call shape: ask for the size, then the/// bytes. `None` for a name the kernel does not answer or an answer that is/// not text; an empty answer is `None` too, because "has not said" is the/// only honest reading of a blank.#[cfg(target_os = "macos")]fn sysctl_string(name: &std::ffi::CStr) -> Option<String> {    let mut size: usize = 0;    // SAFETY: a null buffer with `size` zero asks `sysctlbyname(3)` for the    // length alone; it writes only into `size`, which we own.    let asked = unsafe {        libc::sysctlbyname(            name.as_ptr(),            std::ptr::null_mut(),            &mut size,            std::ptr::null_mut(),            0,        )    };    if asked != 0 || size == 0 {        return None;    }    let mut bytes = vec![0u8; size];    // SAFETY: `sysctlbyname(3)` writes at most `size` bytes into `bytes`, and    // `size` is `bytes`'s own length.    let answered = unsafe {        libc::sysctlbyname(            name.as_ptr(),            bytes.as_mut_ptr().cast(),            &mut size,            std::ptr::null_mut(),            0,        )    };    if answered != 0 {        return None;    }    bytes.truncate(size);    let text = String::from_utf8_lossy(&bytes);    let text = text.trim_end_matches('\0').trim();    (!text.is_empty()).then(|| text.to_string())}/// The Linux reader — the first `model name` in `/proc/cpuinfo`. Not dead code/// on a Mac's conscience: the `rust` job runs this whole crate on Linux.#[cfg(not(target_os = "macos"))]pub fn chip() -> Option<String> {    let text = std::fs::read_to_string(Path::new(PROC_CPUINFO)).ok()?;    parse_cpuinfo_model(&text)}/// The Linux reader — `PRETTY_NAME` from `/etc/os-release`.#[cfg(not(target_os = "macos"))]pub fn os_version() -> Option<String> {    let text = std::fs::read_to_string(Path::new(ETC_OS_RELEASE)).ok()?;    parse_os_release_pretty_name(&text)}/// The first `model name : …` line of a `/proc/cpuinfo`, or `None`.pub fn parse_cpuinfo_model(text: &str) -> Option<String> {    text.lines()        .filter_map(|line| line.split_once(':'))        .find(|(key, _)| key.trim() == "model name")        .map(|(_, value)| value.trim())        .filter(|value| !value.is_empty())        .map(str::to_string)}/// `PRETTY_NAME="…"` out of an `/etc/os-release`, unquoted, or `None`.pub fn parse_os_release_pretty_name(text: &str) -> Option<String> {    text.lines()        .filter_map(|line| line.split_once('='))        .find(|(key, _)| key.trim() == "PRETTY_NAME")        .map(|(_, value)| value.trim().trim_matches('"').trim())        .filter(|value| !value.is_empty())        .map(str::to_string)}#[cfg(target_os = "macos")]pub fn memory() -> Memory {    let total = sysctl_memsize();    let page = page_size();    let free_pages = output_within(        std::process::Command::new("/usr/bin/vm_stat"),        ACCOUNT_ASK_TIMEOUT,    )    .and_then(|out| parse_vm_stat_free_pages(&String::from_utf8_lossy(&out.stdout)))    .unwrap_or(0);    Memory {        total_gb: total as f64 / GIB,        free_pct: free_pct(free_pages.saturating_mul(page), total),    }}#[cfg(target_os = "macos")]fn sysctl_memsize() -> u64 {    let mut value: u64 = 0;    let mut size = std::mem::size_of::<u64>();    let name = c"hw.memsize";    // SAFETY: `sysctlbyname(3)` writes at most `size` bytes into `value`, and    // `size` is `value`'s own size. A refusal leaves the zero we started with.    let answered = unsafe {        libc::sysctlbyname(            name.as_ptr(),            (&raw mut value).cast(),            &mut size,            std::ptr::null_mut(),            0,        )    };    if answered == 0 {        value    } else {        0    }}#[cfg(target_os = "macos")]fn page_size() -> u64 {    // SAFETY: `sysconf(3)` reads a constant.    let answered = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };    if answered > 0 {        answered as u64    } else {        4096    }}#[cfg(not(target_os = "macos"))]pub fn memory() -> Memory {    // The Linux reader. It is not dead code on a Mac's conscience: the `rust`    // job runs this whole crate on Linux, and a sample that answered zero    // there would make every test of it vacuous.    let Ok(text) = std::fs::read_to_string(Path::new(PROC_MEMINFO)) else {        return Memory {            total_gb: 0.0,            free_pct: 0,        };    };    let Some((total_kb, available_kb)) = parse_meminfo(&text) else {        return Memory {            total_gb: 0.0,            free_pct: 0,        };    };    Memory {        total_gb: total_kb as f64 * 1024.0 / GIB,        free_pct: free_pct(available_kb, total_kb),    }}#[cfg(test)]#[path = "machine_tests.rs"]mod machine_tests;/// A headless lanes host measures the same kernel facts as the Mac helper./// tmux owns its sessions; no app, provider accounts or process peaks are claimed.pub fn lane_sample(clock: &dyn Clock, volume: &Path, sessions: u32) -> MachineSample {    let memory = memory();    let mut report = sample(clock, volume, sessions, Default::default(), Default::default(), HandedIn {        binary: SelfReport::default(),        measured: Measured { memory, committed_gb: memory.used_gb(), ..Default::default() },        facts: &facts(volume),    });    report.host_version = format!("machine-report/{}", crate::HOST_VERSION);    report}/// The typed presence columns shared by the Mac mirror and remote reporter./// Facts, app version, accounts and the database's memory budget have separate owners.pub fn reading_columns(sample: &MachineSample) -> serde_json::Map<String, serde_json::Value> {    let wire = serde_json::to_value(sample).expect("machine sample is JSON");    ["cpu_count", "mem_total_gb", "mem_free_pct", "load1", "disk_free_gb",     "sessions_running", "build_lock_held", "mem_committed_gb", "session_peak_gb",     "session_peak_samples", "agents", "host_version", "sampled_at"]        .into_iter().map(|key| (key.to_string(), wire[key].clone())).collect()}