garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/node.rs

raw

//! The node's two sshd hooks, and its GPU readings.
//!
//! sshd (OpenSSH, in the node image) runs:
//!
//! * `AuthorizedKeysCommand midas node authorized-keys %u %k` at every login:
//!   operator keys always; the agent key only while the hub says the node is
//!   leased.
//! * `ForceCommand midas node session` for every session: warnings on stderr,
//!   a log line at the start and at the end, then the agent's command exactly as
//!   typed — `scp`, `rsync` and `git` included; SFTP is passed straight through.
//!
//! Configuration is `/config/node.env` (written by the installer): `MIDAS_NODE`,
//! `MIDAS_HUB` (e.g. `http://10.44.0.1:4791`), `MIDAS_GUARD_WARN` and
//! `MIDAS_GUARD_STOP` (percent of the shared GPU pool), and the agent keys in
//! `/config/authorized_keys`. `/config/bot.env`, if the machine's owner set one
//! (`midas bot setup`), is for bots only (`bot`).

use std::collections::HashMap;
use std::fs;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};

use anyhow::Result;
use serde_json::{json, Value};

use crate::events;
use crate::hub;

pub(crate) fn config_dir() -> PathBuf {
    PathBuf::from(std::env::var("MIDAS_CONFIG").unwrap_or_else(|_| "/config".into()))
}

/// The node's own log lives on its volume; every event is also sent to the hub.
fn log_root() -> PathBuf {
    PathBuf::from(std::env::var("MIDAS_NODE_LOG").unwrap_or_else(|_| "/work".into()))
}

pub(crate) struct Config {
    pub node: String,
    pub hub: String,
    warn_pct: f64,
    stop_pct: f64,
    /// The recipe the machine's owner set this node up from (`setup::recipe`);
    /// none for a node set up before recipes were recorded.
    recipe: Option<String>,
}

pub(crate) fn config() -> Config {
    let text = fs::read_to_string(config_dir().join("node.env")).unwrap_or_default();
    let mut m: HashMap<String, String> = HashMap::new();
    for line in text.lines() {
        if let Some((k, v)) = line.split_once('=') {
            m.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
        }
    }
    let num = |k: &str, d: f64| m.get(k).and_then(|v| v.parse().ok()).unwrap_or(d);
    Config {
        node: m.get("MIDAS_NODE").cloned().unwrap_or_else(|| "unknown".into()),
        // The installer writes MIDAS_HUB; without it, what any client would use
        // (MIDAS_HUB in the environment, else hub.conf, else loopback).
        hub: m.get("MIDAS_HUB").cloned().unwrap_or_else(crate::client::hub_url),
        warn_pct: num("MIDAS_GUARD_WARN", 80.0),
        stop_pct: num("MIDAS_GUARD_STOP", 92.0),
        recipe: m.get("MIDAS_RECIPE").filter(|r| !r.is_empty()).cloned(),
    }
}

/// Log locally and, best effort, on the hub.
pub(crate) fn emit(cfg: &Config, kind: &str, fields: Value) {
    let body = log_event(cfg, kind, fields);
    let _ = hub::request(&cfg.hub, "POST", "/v1/events", Some(&body));
}

/// Into the node's own log; returns the hub's copy (no time: the hub stamps it).
fn log_event(cfg: &Config, kind: &str, mut fields: Value) -> String {
    fields["node"] = json!(cfg.node);
    events::emit_at(&log_root(), kind, fields.clone());
    fields["kind"] = json!(kind);
    fields.to_string()
}

/// As `emit`, but the hub's copy goes from a detached child, so the session
/// does not wait the round trip to the hub (0.1 s from a Mac's VM, up to a
/// second from the deck) before it runs the command or hands back its result.
/// The child's stdio is /dev/null, or sshd would hold the session open until it
/// finished. Returns a token that reads end-of-file once this child is done:
/// passed as `after` to the next one, it keeps the hub's log in order (an
/// `open` before its `close`). Call it with no other thread running: only the
/// forking thread survives a fork.
fn emit_detached(cfg: &Config, kind: &str, fields: Value, after: Option<OwnedFd>) -> Option<OwnedFd> {
    let body = log_event(cfg, kind, fields);
    let mut fds = [-1; 2];
    // SAFETY: pipe(2), fcntl(2), fork(2) and the rest on fds this function
    // owns, from a single-threaded process; the child leaves with _exit, running
    // no destructors, and its exit closes the write end the token waits on.
    unsafe {
        let piped = libc::pipe(fds.as_mut_ptr()) == 0;
        if piped {
            // Not into the command the session runs.
            libc::fcntl(fds[0], libc::F_SETFD, libc::FD_CLOEXEC);
            libc::fcntl(fds[1], libc::F_SETFD, libc::FD_CLOEXEC);
        }
        match libc::fork() {
            0 => {
                libc::setsid();
                // Again, and this one leaves at once: the work goes on in a
                // grandchild that init reaps, not a zombie under the session
                // for as long as its command runs.
                if libc::fork() > 0 {
                    libc::_exit(0);
                }
                let null = libc::open(c"/dev/null".as_ptr(), libc::O_RDWR);
                if null >= 0 {
                    for fd in 0..3 {
                        libc::dup2(null, fd);
                    }
                }
                if piped {
                    libc::close(fds[0]);
                }
                if let Some(a) = after {
                    let mut buf = [0u8; 8];
                    while libc::read(a.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) > 0 {}
                }
                let _ = hub::request(&cfg.hub, "POST", "/v1/events", Some(&body));
                libc::_exit(0);
            }
            -1 => {
                if piped {
                    libc::close(fds[0]);
                    libc::close(fds[1]);
                }
                let _ = hub::request(&cfg.hub, "POST", "/v1/events", Some(&body));
                None
            }
            child => {
                libc::waitpid(child, std::ptr::null_mut(), 0);
                piped.then(|| {
                    libc::close(fds[1]);
                    OwnedFd::from_raw_fd(fds[0])
                })
            }
        }
    }
}

pub(crate) enum Lease {
    /// `mode` is the lease's, `build` or `bot` (`registry::Mode`).
    Held { owner: String, purpose: Option<String>, since: i64, mode: String },
    Free,
    Unknown(String),
}

pub(crate) fn lease(cfg: &Config) -> Lease {
    match hub::request(&cfg.hub, "GET", &format!("/v1/lease/{}", cfg.node), None) {
        Ok((200, body)) => match serde_json::from_str::<Value>(&body) {
            Ok(v) if v["leased"] == true => Lease::Held {
                owner: v["owner"].as_str().unwrap_or("?").to_string(),
                purpose: v["purpose"].as_str().map(str::to_string),
                since: v["since"].as_i64().unwrap_or(0),
                // A hub from before modes leases for building only.
                mode: v["mode"].as_str().unwrap_or("build").to_string(),
            },
            Ok(_) => Lease::Free,
            Err(e) => Lease::Unknown(format!("hub answered something that is not JSON: {e}")),
        },
        Ok((code, _)) => Lease::Unknown(format!("hub answered HTTP {code}")),
        Err(e) => Lease::Unknown(format!("hub unreachable: {e}")),
    }
}

/// The node's checkout, where sessions start and the flush applies.
pub const CHECKOUT: &str = "/work/checkout";

/// `AuthorizedKeysCommand`: print the agent keys if a session may start.
///
/// Fails *open* when the hub cannot be asked: a missing lease is a fairness
/// problem, not a security one — the key is still required — and a hub outage
/// must not stop every build in the workspace. The session then says so on stderr.
pub fn authorized_keys(user: &str, offered: Option<&str>) -> Result<i32> {
    let cfg = config();
    if user != "build" {
        return Ok(0);
    }
    // The workspace's own keys (the hub's reachability check and warmer) get in
    // whether or not the node is leased: "is the node up?" is asked of a free
    // node, and the warmer takes its own lease before it changes anything. Told
    // which key is on offer (%k), an operator key is answered without asking
    // the hub, so a reachability probe logs no refusal every ten minutes.
    let operators = fs::read_to_string(config_dir().join("operator_keys")).unwrap_or_default();
    if let Some(k) = offered.filter(|k| !k.is_empty()) {
        if let Some(line) = operators.lines().find(|l| l.split_whitespace().nth(1) == Some(k)) {
            println!("{line}");
            return Ok(0);
        }
    } else {
        print!("{operators}");
    }
    let keys = fs::read_to_string(config_dir().join("authorized_keys")).unwrap_or_default();
    match lease(&cfg) {
        Lease::Held { .. } => print!("{keys}"),
        Lease::Free => {
            emit(&cfg, "ssh_refused", json!({"why": "node is not leased"}));
            eprintln!("midas: {} is not leased; refusing", cfg.node);
        }
        Lease::Unknown(why) => {
            emit(&cfg, "hub_unreachable", json!({"why": why, "decision": "allowed"}));
            print!("{keys}");
        }
    }
    Ok(0)
}

#[derive(Default)]
pub struct GpuReading {
    pub vram_used: u64,
    pub vram_total: u64,
    pub gtt_used: u64,
    pub gtt_total: u64,
}

impl GpuReading {
    pub fn gtt_pct(&self) -> f64 {
        if self.gtt_total == 0 { 0.0 } else { self.gtt_used as f64 * 100.0 / self.gtt_total as f64 }
    }
    pub fn vram_pct(&self) -> f64 {
        if self.vram_total == 0 { 0.0 } else { self.vram_used as f64 * 100.0 / self.vram_total as f64 }
    }
}

/// amdgpu's own counters. The shared pool (GTT) is the one that froze a handheld build machine.
pub fn gpu() -> Option<GpuReading> {
    let dev = fs::read_dir("/sys/class/drm")
        .ok()?
        .flatten()
        .map(|e| e.path().join("device"))
        .find(|d| d.join("mem_info_gtt_total").exists())?;
    let read = |n: &str| -> u64 {
        fs::read_to_string(dev.join(n)).ok().and_then(|t| t.trim().parse().ok()).unwrap_or(0)
    };
    Some(GpuReading {
        vram_used: read("mem_info_vram_used"),
        vram_total: read("mem_info_vram_total"),
        gtt_used: read("mem_info_gtt_used"),
        gtt_total: read("mem_info_gtt_total"),
    })
}

/// Shared GPU memory each process holds, from amdgpu's per-fd usage report
/// (`drm-memory-gtt` in `/proc/<pid>/fdinfo`): `(pid, MiB, command)`, largest first.
fn gtt_by_process() -> Vec<(u32, u64, String)> {
    let mut out = Vec::new();
    let Ok(procs) = fs::read_dir("/proc") else { return out };
    for p in procs.flatten() {
        let Ok(pid) = p.file_name().to_string_lossy().parse::<u32>() else { continue };
        let Ok(fds) = fs::read_dir(format!("/proc/{pid}/fdinfo")) else { continue };
        let mut seen = std::collections::HashSet::new();
        let mut kib = 0u64;
        for fd in fds.flatten() {
            let Ok(t) = fs::read_to_string(fd.path()) else { continue };
            if !t.contains("drm-driver:\tamdgpu") && !t.contains("drm-driver: amdgpu") {
                continue;
            }
            // One GPU context can be open on several fds; count each client once.
            let client = t.lines().find(|l| l.starts_with("drm-client-id")).unwrap_or("").to_string();
            if !seen.insert(client) {
                continue;
            }
            if let Some(v) = t.lines().find(|l| l.starts_with("drm-memory-gtt:")).and_then(|l| l.split_whitespace().nth(1)) {
                kib += v.parse::<u64>().unwrap_or(0);
            }
        }
        if kib > 0 {
            let cmd = fs::read_to_string(format!("/proc/{pid}/cmdline"))
                .unwrap_or_default()
                .replace('\0', " ")
                .chars()
                .take(120)
                .collect::<String>();
            out.push((pid, kib / 1024, cmd.trim().to_string()));
        }
    }
    out.sort_by(|a, b| b.1.cmp(&a.1));
    out
}

const GUARD_NOTE: &str = "/work/.midas-guard-last";

/// The GPU memory guard (DESIGN.md §9): the machine stays up first, the agent is
/// told second. Measured on an AMD APU on 2026-10-11: shared GPU memory (GTT) is
/// **not** charged to the container's memory cgroup — a capture added 3.7 GB of
/// GTT while the container's anon memory rose by 2.4 GB — so `--memory` cannot
/// stop the freeze, and this is what does.
///
/// Above the warn level it logs once per crossing (sessions warn on their own).
/// At the stop level it asks the process holding the most shared GPU memory to
/// exit — SIGTERM, never SIGKILL: a process stuck in the kernel's swap-out
/// cannot exit, and a kill there is what left the 2026-10-10 zombie — and writes
/// a note the next session shows the agent.
/// What the node looks like right now: its cgroup's memory against its limit
/// (and how many OOM kills it has seen), the work volume's free space, the load,
/// the GPU pools, and what the checkout is at and warm for. Sent to the hub every
/// minute, so `midas status` can say "gpu-1: 7 % GPU pool, 3.1 of 10 GiB, 95 GB
/// free, warm at ec992a8" without anybody holding the node.
pub fn reading() -> Value {
    let cg = |f: &str| fs::read_to_string(format!("/sys/fs/cgroup/{f}")).ok();
    let num = |t: Option<String>| t.and_then(|t| t.trim().parse::<u64>().ok());
    let oom = cg("memory.events").and_then(|t| {
        t.lines().find_map(|l| l.strip_prefix("oom_kill ").and_then(|v| v.trim().parse::<u64>().ok()))
    });
    let (disk_free, disk_total) = crate::util::disk_space(std::path::Path::new("/work")).unzip();
    let load = fs::read_to_string("/proc/loadavg").ok()
        .and_then(|t| t.split_whitespace().next().and_then(|v| v.parse::<f64>().ok()))
        .or_else(macos::load);
    let read = |p: &str| fs::read_to_string(Path::new(CHECKOUT).join(p)).ok().map(|t| t.trim().to_string());
    let read_mark = |p: &str| fs::read_to_string(p).ok().map(|t| t.trim().to_string());
    let g = gpu();
    json!({
        "mem_used": num(cg("memory.current")).or_else(|| macos::memory().map(|m| m.0)),
        // Process memory: what the limit actually bites on. memory.current also
        // counts page cache, which a build fills and the kernel gives back.
        "mem_anon": mem_anon(),
        "mem_max": num(cg("memory.max")).or_else(|| macos::memory().map(|m| m.1)),
        "oom_kills": oom,
        "disk_free": disk_free,
        // The volume's size and the CPUs this node may use (its cgroup's quota on
        // Linux): what the web page's disk and load meters are drawn against.
        "disk_total": disk_total,
        "load": load,
        "cpus": std::thread::available_parallelism().ok().map(|n| n.get()),
        "gtt_pct": g.as_ref().map(|g| (g.gtt_pct() * 10.0).round() / 10.0),
        "vram_pct": g.as_ref().map(|g| (g.vram_pct() * 10.0).round() / 10.0),
        "head": read(".git/HEAD"),
        // Open ssh sessions: a lease with none for half an hour is given back
        // (the hub's idle rule), one with a long build running is not.
        "sessions": ssh_sessions(),
        // What those sessions run, and how long each has done nothing (stall.rs).
        "commands": quiet_commands(),
        // A bot running here (`midas node bot`): for a bot lease, as good as a
        // session open.
        "bot": crate::bot::reading(),
        "warm": read_mark("/work/.warm"),
        "warm_optional": read_mark("/work/.warm-optional"),
        "warm_age_s": fs::metadata("/work/.warm").ok()
            .and_then(|m| m.modified().ok()).and_then(|t| t.elapsed().ok()).map(|d| d.as_secs()),
        // Measured every ten minutes by the guard; a du of a 20 GB tree is not free.
        "target_bytes": fs::read_to_string(TARGET_SIZE).ok().and_then(|t| t.trim().parse::<u64>().ok()),
        // The GPU memory cap in force, if the machine delegates dmem ("max" = none).
        "dmem_max": fs::read_to_string("/sys/fs/cgroup/dmem.max").ok().map(|t| t.trim().to_string()),
        "version": crate::VERSION,
        "recipe": config().recipe,
    })
}

/// The process memory in use now: the cgroup's anon pages on Linux, the
/// machine's active, wired and compressed pages on macOS.
fn mem_anon() -> Option<u64> {
    fs::read_to_string("/sys/fs/cgroup/memory.stat").ok()
        .and_then(|t| t.lines().find_map(|l| l.strip_prefix("anon ").and_then(|v| v.trim().parse::<u64>().ok())))
        .or_else(|| macos::memory().map(|m| m.0))
}

/// The highest `mem_anon` since the last heartbeat, sampled every ten seconds:
/// a link that peaks between two minute readings is what sizes a node, and
/// one reading a minute misses it (usage.rs keeps them).
static MEM_PEAK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

fn sample_peak() {
    if let Some(m) = mem_anon() {
        MEM_PEAK.fetch_max(m, std::sync::atomic::Ordering::Relaxed);
    }
}

/// The reading the heartbeat sends: [`reading`] and the peak since the last one.
fn heartbeat_reading() -> Value {
    let mut r = reading();
    let peak = MEM_PEAK.swap(0, std::sync::atomic::Ordering::Relaxed);
    let now = r["mem_anon"].as_u64().unwrap_or(0);
    if peak > 0 || now > 0 {
        r["mem_peak"] = json!(peak.max(now));
    }
    r
}

pub fn guard() -> Result<i32> {
    let cfg = config();
    let mut warned = false;
    let mut last_stop: Option<std::time::Instant> = None;
    let mut tick: u64 = 0;
    loop {
        // The node's heartbeat: a reading to the hub every minute.
        if tick % 300 == 0 {
            // On its own thread: a du of a 20 GB tree takes seconds, and the
            // guard must not stop watching the GPU pool for that long.
            std::thread::spawn(|| {
                measure_target();
                trim_target(&config());
                free_up_disk(&config());
            });
        }
        if tick % 30 == 0 {
            // A bot lives exactly as long as its bot lease: one left behind by a
            // release, a lapse or a `take` in build mode is stopped here, before
            // the reading says what runs.
            crate::bot::enforce(&cfg);
            let _ = hub::request(&cfg.hub, "POST", &format!("/v1/readings/{}", cfg.node), Some(&heartbeat_reading().to_string()));
        } else if tick % 5 == 0 {
            sample_peak();
        }
        tick += 1;
        if let Some(g) = gpu() {
            let pct = g.gtt_pct();
            if pct >= cfg.warn_pct && !warned {
                warned = true;
                emit(&cfg, "guard", json!({"stage": "warn", "gtt_pct": (pct * 10.0).round() / 10.0, "gtt_used_mb": g.gtt_used >> 20}));
            } else if pct < cfg.warn_pct - 5.0 {
                warned = false;
            }
            let cooling = last_stop.is_some_and(|t| t.elapsed().as_secs() < 20);
            if pct >= cfg.stop_pct && !cooling {
                let holders = gtt_by_process();
                if holders.is_empty() {
                    emit(&cfg, "guard", json!({
                        "stage": "stop", "gtt_pct": (pct * 10.0).round() / 10.0,
                        "signalled": false, "why": "no process visible holding GPU memory",
                    }));
                }
                if let Some((pid, mib, cmd)) = holders.into_iter().next() {
                    // SAFETY: kill(2) with a pid we read from /proc and SIGTERM.
                    let rc = unsafe { libc::kill(pid as i32, libc::SIGTERM) };
                    let note = format!(
                        "the GPU guard stopped pid {pid} ({cmd}) at {} — shared GPU memory was at {pct:.0} % \
                         ({} of {} MB) and it held {mib} MB. Lower its settings or wait for the pool to drain.",
                        chrono::Local::now().format("%H:%M:%S"),
                        g.gtt_used >> 20,
                        g.gtt_total >> 20
                    );
                    let _ = fs::write(GUARD_NOTE, &note);
                    emit(&cfg, "guard", json!({
                        "stage": "stop", "gtt_pct": (pct * 10.0).round() / 10.0, "pid": pid,
                        "command": cmd, "held_mb": mib, "signalled": rc == 0,
                    }));
                }
                last_stop = Some(std::time::Instant::now());
            }
        }
        std::thread::sleep(std::time::Duration::from_secs(2));
    }
}

/// The note the guard left, if it acted in the last hour — shown to the next
/// session only, then set aside, so the agent learns why its capture ended
/// without the line repeating on every command after it (it did, twice per ssh).
fn guard_note() -> Option<String> {
    let md = fs::metadata(GUARD_NOTE).ok()?;
    let age = md.modified().ok()?.elapsed().ok()?;
    let note = (age.as_secs() < 3600).then(|| fs::read_to_string(GUARD_NOTE).ok()).flatten();
    let _ = fs::rename(GUARD_NOTE, format!("{GUARD_NOTE}.shown"));
    note
}

pub fn gpu_cmd() -> Result<i32> {
    match gpu() {
        Some(g) => println!(
            "vram {} / {} MB ({:.0} %) · shared (GTT) {} / {} MB ({:.0} %)",
            g.vram_used >> 20, g.vram_total >> 20, g.vram_pct(),
            g.gtt_used >> 20, g.gtt_total >> 20, g.gtt_pct()
        ),
        None => println!("no amdgpu memory counters on this machine"),
    }
    Ok(0)
}

/// The sftp-server to run for sshd's subsystem command `c`: that path when it
/// is one, else the first that exists of Linux's and macOS's.
fn sftp_server(c: &str) -> String {
    if c.starts_with('/') && Path::new(c).exists() {
        return c.to_string();
    }
    ["/usr/lib/ssh/sftp-server", "/usr/libexec/sftp-server", "/usr/lib/openssh/sftp-server"]
        .into_iter()
        .find(|p| Path::new(p).exists())
        .unwrap_or("/usr/lib/ssh/sftp-server")
        .to_string()
}

/// `ForceCommand`: everything that runs on the node runs through here.
pub fn session() -> Result<i32> {
    let cfg = config();
    let original = std::env::var("SSH_ORIGINAL_COMMAND").ok();
    let peer = std::env::var("SSH_CONNECTION").ok().and_then(|c| c.split_whitespace().next().map(str::to_string));

    // SFTP is a binary protocol on stdout and stderr: no warnings, no wrapper.
    // The server is the one sshd_config names (/usr/libexec on macOS, where a
    // fixed Linux path made every scp from a Mac node "Connection closed").
    if let Some(c) = &original {
        if c.ends_with("sftp-server") || c == "internal-sftp" {
            let server = sftp_server(c);
            let err = Command::new(&server).exec();
            anyhow::bail!("could not start {server}: {err}");
        }
    }

    let command_for_log: Option<String> = original.as_ref().map(|c| c.chars().take(200).collect());
    // Every session keeps the lease alive and says what it ran, as a cargo build
    // in a local node does through the wrapper. The flush's own sessions
    // (`midas node apply`) are bookkeeping, not activity. Asked beside the
    // lease rather than after it: each is a round trip to the hub, and every
    // ssh waits for them. The hub renews only a node that is leased.
    let lease_now = std::thread::scope(|s| {
        if original.as_deref() != Some("midas node apply") {
            let body = json!({"command": command_for_log.clone().unwrap_or_else(|| "interactive shell".into())});
            let hub = &cfg.hub;
            let node = &cfg.node;
            s.spawn(move || hub::request(hub, "POST", &format!("/v1/renew/{node}"), Some(&body.to_string())));
        }
        lease(&cfg)
    });
    // Warnings go to stderr: an agent reads it with every command's output, and
    // no protocol that runs over a session (scp, rsync, git) reads it.
    let holder = match lease_now {
        Lease::Held { owner, purpose, since, .. } => {
            handover(&cfg, &owner, since);
            Some((owner, purpose))
        }
        Lease::Free => {
            eprintln!("midas: warning — {} is not leased. Take it first: midas take --node {} (only the workspace's operator key gets in unleased)", cfg.node, cfg.node);
            None
        }
        Lease::Unknown(why) => {
            eprintln!("midas: warning — could not ask the hub who holds {} ({why})", cfg.node);
            None
        }
    };
    if let Some(note) = guard_note() {
        eprintln!("midas: {note}");
    }
    let reading = gpu();
    if let Some(g) = &reading {
        let pct = g.gtt_pct();
        if pct >= cfg.stop_pct {
            eprintln!(
                "midas: STOP — the node's shared GPU memory is at {pct:.0} % ({} of {} MB). \
                 Anything GPU-heavy started now is likely to freeze this machine; \
                 wait for it to drop, or lower the capture's settings.",
                g.gtt_used >> 20, g.gtt_total >> 20
            );
        } else if pct >= cfg.warn_pct {
            eprintln!(
                "midas: warning — the node's shared GPU memory is at {pct:.0} % ({} of {} MB); \
                 a capture now may freeze this machine.",
                g.gtt_used >> 20, g.gtt_total >> 20
            );
        }
        if pct >= cfg.warn_pct {
            emit(&cfg, "guard", json!({
                "stage": if pct >= cfg.stop_pct { "stop" } else { "warn" },
                "gtt_pct": (pct * 10.0).round() / 10.0, "gtt_used_mb": g.gtt_used >> 20,
                "vram_pct": (g.vram_pct() * 10.0).round() / 10.0,
            }));
        }
    }

    // Edits held back while another command ran (flush::apply): a build or a
    // test run now would build the files as they were, and its result reads as
    // the edits' own. It waits for the running command, then applies them; a
    // minute on, it is refused rather than run on stale files. Anything else —
    // a look at a log, a copy — runs at once, as it always did.
    if crate::flush::pending() && original.as_deref().is_some_and(builds) {
        let deadline = Instant::now() + PENDING_WAIT;
        let mut said = false;
        let running = loop {
            let running = running_commands();
            if running.is_empty() || Instant::now() >= deadline {
                break running;
            }
            if !said {
                eprintln!("midas: your latest edits wait until `{}` ends here; waiting up to {} s for it",
                          running[0].chars().take(80).collect::<String>(), PENDING_WAIT.as_secs());
                said = true;
            }
            std::thread::sleep(Duration::from_secs(1));
        };
        if running.is_empty() {
            match crate::flush::apply_pending() {
                Ok(0) => {}
                Ok(_) | Err(_) => eprintln!("midas: your held-back edits could not be applied here; the next ssh sends them again"),
            }
        } else {
            eprintln!(
                "midas: not run — `{}` still runs on {} from this worktree, and your edits since are not in the \
                 checkout yet, so this would build the old files. Wait for it (or stop it), then run this again; \
                 MIDAS_SYNC=force on the ssh applies them under it anyway.",
                running[0].chars().take(80).collect::<String>(), cfg.node
            );
            emit(&cfg, "stale_refused", json!({"actor": holder.as_ref().map(|(o, _)| o.clone()), "command": command_for_log,
                                               "running": running[0].chars().take(200).collect::<String>()}));
            return Ok(75);
        }
    }

    let actor = holder.as_ref().map(|(o, _)| o.clone());
    let opened = emit_detached(&cfg, "ssh_session", json!({
        "phase": "open", "actor": actor, "command": command_for_log, "peer": peer,
        "gtt_pct": reading.as_ref().map(|g| (g.gtt_pct() * 10.0).round() / 10.0),
    }), None);

    let started = Instant::now();
    let shell = if Path::new("/bin/bash").exists() { "/bin/bash" } else { "/bin/sh" };
    let mut cmd = Command::new(shell);
    // Sessions start in the checkout, so `ssh gpu-1 'cargo test'` builds the
    // worktree the flush just sent, and a relative scp path means a file in it:
    // the one of the repository last sent, when that is not the node's own.
    let current = std::fs::read_to_string(crate::flush::CURRENT).ok().map(|p| p.trim().to_string());
    let start = current.filter(|p| Path::new(p).join(".git").exists()).unwrap_or_else(|| CHECKOUT.to_string());
    if Path::new(&start).join(".git").exists() {
        cmd.current_dir(&start);
    }
    match &original {
        Some(c) => {
            cmd.arg("-lc").arg(c);
        }
        None => {
            cmd.arg("-l");
        }
    }
    // Low disk, said before the build that would hit it rather than after: a
    // full volume truncates files mid-write and reads as a compiler bug.
    if let Some(free) = crate::node::reading()["disk_free"].as_u64().filter(|f| *f < LOW_DISK) {
        eprintln!(
            "midas: warning — {} has {} GB free on its work volume. A build can fail \
             strangely when it runs out; `cargo clean -p <crate>` or `rm -rf target/debug/incremental` frees room.",
            cfg.node, free / 1_000_000_000
        );
    }
    // What a command left in /tmp is usually what it was run for (a capture, a
    // dump). Listing it saves a round trip to find out what to fetch.
    let plumbing = original.as_deref().is_some_and(|c| {
        c == "midas node apply" || c.starts_with("scp ") || c.starts_with("rsync ") || c.starts_with("git-")
    });
    let run_started = std::time::SystemTime::now();
    let ooms_before = oom_kills();
    // A command running here holds back the flush of another ssh from the
    // same worktree, which would change files under it (`running_commands`).
    // Not a bot's MCP relay, which stays open as long as its agent talks to it.
    let relay = original.as_deref() == Some("midas node bot mcp");
    let running = (!plumbing && !relay && original.is_some()).then(|| {
        let m = Path::new(RUNNING).join(std::process::id().to_string());
        let _ = fs::create_dir_all(RUNNING);
        let _ = fs::write(&m, command_for_log.as_deref().unwrap_or(""));
        m
    });
    // An agent's command, its output not a terminal: watched, so one that does
    // nothing cannot hold the session for ever (stall.rs). A terminal session
    // stays in sshd's own process group, where job control expects it.
    // SAFETY: isatty(3) only asks about a descriptor.
    let tty = unsafe { libc::isatty(0) == 1 || libc::isatty(1) == 1 };
    let watch = running.as_ref().filter(|_| !tty).and(original.as_deref()).and_then(crate::stall::limits_for);
    let status = match watch {
        Some(limits) => {
            let what = command_for_log.as_deref().unwrap_or("").chars().take(80).collect::<String>();
            crate::stall::run(cmd, limits, running.as_deref(), || others_moving(running.as_deref(), limits), |said| {
                use crate::stall::Said;
                let mins = |d: Duration| match d.as_secs() { s if s < 120 => format!("{s} s"), s => format!("{} minutes", s / 60) };
                match said {
                    Said::Quiet(q) => {
                        eprintln!("midas: `{what}` has printed nothing and used no CPU for {} on {}; it is \
                                   stopped at {} of it unless it moves (MIDAS_STALL=off as its first word lets it be).",
                                  mins(q), cfg.node, mins(limits.stop));
                        emit(&cfg, "stalled", json!({"stage": "warn", "actor": actor, "command": command_for_log, "quiet_s": q.as_secs()}));
                    }
                    Said::Stopping(q, left) => {
                        eprintln!("{}", crate::stall::stopped_words(&what, &cfg.node, &mins(q), &left));
                        emit(&cfg, "stalled", json!({"stage": "stop", "actor": actor, "command": command_for_log,
                                                     "quiet_s": q.as_secs(), "group": left}));
                    }
                    Said::Leftovers(held) => {
                        eprintln!("midas: `{what}` ended, but left {} process(es) holding its output open ({}); the \
                                   session ends without them. Start one meant to outlive the command with its output \
                                   redirected: nohup … >/tmp/x.log 2>&1 &",
                                  held.len(), held.join("; "));
                        emit(&cfg, "left_running", json!({"actor": actor, "command": command_for_log, "held": held}));
                    }
                }
            })
        }
        None => cmd.status(),
    };
    if let Some(m) = running {
        let _ = fs::remove_file(m);
    }
    if !plumbing && original.is_some() {
        let fresh = new_files("/tmp", run_started);
        if !fresh.is_empty() {
            let shown: Vec<String> = fresh.iter().take(6).map(|(p, n)| format!("{p} ({})", human(*n))).collect();
            let more = if fresh.len() > 6 { format!(" and {} more", fresh.len() - 6) } else { String::new() };
            eprintln!("midas: new in /tmp: {}{more} — scp {}:{} .", shown.join(", "), cfg.node, fresh[0].0);
        }
    }
    let (code, signal) = match &status {
        Ok(s) => (s.code(), s.signal()),
        Err(_) => (Some(127), None),
    };
    // A process the node's memory limit killed dies of SIGKILL with nothing on
    // its stderr — rustc says "signal: 9", cargo says "Killed" — which reads as a
    // crash. The cgroup counted it; say so, in words, with the limit.
    let ooms = oom_kills().saturating_sub(ooms_before);
    if ooms > 0 {
        let limit = fs::read_to_string("/sys/fs/cgroup/memory.max").ok()
            .and_then(|t| t.trim().parse::<u64>().ok())
            .map(|b| format!("{:.0} GiB", b as f64 / (1u64 << 30) as f64))
            .unwrap_or_else(|| "its".into());
        eprintln!(
            "midas: {ooms} process(es) in this session were killed by {}'s {limit} memory limit, \
             not by a bug — fewer parallel jobs (cargo -j) or a smaller capture will fit.",
            cfg.node
        );
        emit(&cfg, "oom_kill", json!({"actor": actor, "command": command_for_log, "count": ooms}));
    }
    emit_detached(&cfg, "ssh_session", json!({
        "phase": "close", "actor": actor, "command": command_for_log,
        "exit": code, "signal": signal, "duration_s": started.elapsed().as_secs(), "oom_kills": ooms,
    }), opened);
    Ok(code.unwrap_or_else(|| 128 + signal.unwrap_or(0)))
}

/// How long a build waits for a running command before its held-back edits
/// can be applied (`session`).
const PENDING_WAIT: Duration = Duration::from_secs(60);

/// Whether a command builds or tests what is in the checkout: the first word
/// that is not a `cd …`, a variable or a wrapper (`time`, `nice`, `timeout N`,
/// `env`) is a build tool. What a held-back sync matters to.
fn builds(command: &str) -> bool {
    const TOOLS: [&str; 18] = ["cargo", "bun", "bunx", "npm", "npx", "pnpm", "yarn", "make", "cmake", "ninja", "go",
                               "pytest", "just", "swift", "xcodebuild", "gradle", "./gradlew", "mvn"];
    command.split(['&', ';', '|', '\n']).map(str::trim).filter(|p| !p.is_empty()).any(|part| {
        let mut words = part.split_whitespace().peekable();
        while let Some(w) = words.peek() {
            if *w == "cd" {
                return false; // this part only moves; the next one is the command
            }
            let wrapper = matches!(*w, "time" | "nice" | "env" | "exec" | "command") || w.contains('=');
            if *w == "timeout" {
                words.next();
                words.next(); // its duration
                continue;
            }
            if !wrapper {
                break;
            }
            words.next();
        }
        words.next().is_some_and(|w| TOOLS.contains(&w.rsplit('/').next().unwrap_or(w)) || TOOLS.contains(&w))
    })
}

/// One file per command running in an ssh session here, named by its
/// session's pid and holding the command.
const RUNNING: &str = "/work/.midas-running";

/// The commands ssh sessions are running here now (not scp, rsync, git or
/// the flush's own apply). A marker whose session is gone — killed with its
/// connection before it could clean up — is removed.
pub fn running_commands() -> Vec<String> {
    running_in(Path::new(RUNNING))
}

fn running_in(dir: &Path) -> Vec<String> {
    let mine = std::process::id();
    fs::read_dir(dir).into_iter().flatten().flatten().filter_map(|e| {
        let pid: i32 = e.file_name().to_string_lossy().parse().ok()?;
        // SAFETY: signal 0 sends nothing; it only asks whether the pid exists.
        let alive = unsafe { libc::kill(pid, 0) } == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM);
        if !alive {
            let _ = fs::remove_file(e.path());
            return None;
        }
        (pid as u32 != mine).then(|| fs::read_to_string(e.path()).unwrap_or_default())
    }).collect()
}

/// The commands running here and how long each has been quiet: its marker's
/// age, which the stall watch touches at every sign of progress (stall.rs).
/// For the heartbeat, so the page can say a session's command does nothing.
fn quiet_commands() -> Vec<Value> {
    let now = std::time::SystemTime::now();
    running_commands();  // clears the markers of sessions that are gone
    fs::read_dir(RUNNING).into_iter().flatten().flatten().filter_map(|e| {
        let quiet = now.duration_since(e.metadata().ok()?.modified().ok()?).ok()?;
        Some(json!({"command": fs::read_to_string(e.path()).ok()?.chars().take(120).collect::<String>(), "quiet_s": quiet.as_secs()}))
    }).collect()
}

/// Whether another command running here moved lately: a quiet cargo may be
/// waiting for the build directory's lock while the build that holds it works.
fn others_moving(mine: Option<&Path>, limits: crate::stall::Limits) -> bool {
    let lately = (limits.stop / 5).min(Duration::from_secs(120));
    let now = std::time::SystemTime::now();
    running_commands();
    fs::read_dir(RUNNING).into_iter().flatten().flatten()
        .filter(|e| Some(e.path().as_path()) != mine)
        .filter_map(|e| now.duration_since(e.metadata().ok()?.modified().ok()?).ok())
        .any(|age| age < lately)
}

/// The cgroup's OOM-kill count (the node's own memory limit, not the host's).
fn oom_kills() -> u64 {
    fs::read_to_string("/sys/fs/cgroup/memory.events")
        .ok()
        .and_then(|t| t.lines().find_map(|l| l.strip_prefix("oom_kill ").and_then(|v| v.trim().parse().ok())))
        .unwrap_or(0)
}

const LEASE_MARK: &str = "/work/.midas-lease";

/// The first session under a new lease clears what the previous holder left
/// running: its processes (a forgotten capture holding the GPU pool, a test
/// server on a port) and its files in /tmp. The checkout is the flush's
/// business; the warm build directory is everybody's and stays.
///
/// Spared: the guard, the sshd sessions, and this session's own ancestry —
/// which is also why it only ever runs from a session.
fn handover(cfg: &Config, owner: &str, since: i64) {
    let mark = format!("{owner} {since}");
    let previous = fs::read_to_string(LEASE_MARK).unwrap_or_default();
    if previous.trim() == mark {
        return;
    }
    // Written first: a second session racing this one must not clear the first's work.
    let _ = fs::write(LEASE_MARK, &mark);
    if previous.trim().is_empty() {
        return; // first lease this node has seen: nothing of anyone's to clear
    }
    let me = unsafe { libc::getuid() };
    let procs = crate::procs::all();
    let ancestors = crate::procs::ancestry(&procs);
    let mut killed = Vec::new();
    for p in &procs {
        if p.uid != me || ancestors.contains(&p.pid) {
            continue;
        }
        let cmd = &p.cmd;
        if cmd.contains("midas node guard") || cmd.starts_with("sshd") || cmd.contains("sshd-session") || cmd.is_empty() {
            continue;
        }
        // SAFETY: kill(2) on a pid owned by this same user, with SIGTERM.
        if unsafe { libc::kill(p.pid as i32, libc::SIGTERM) } == 0 {
            killed.push(format!("{} {}", p.pid, cmd.chars().take(60).collect::<String>()));
        }
    }
    // The previous holder's bot went with the processes above; its record and
    // its log go too, so this holder starts with no bot and nothing to read.
    let bot = crate::bot::clear();
    let mut removed = 0;
    if let Ok(rd) = fs::read_dir("/tmp") {
        for e in rd.flatten() {
            let ours = std::os::unix::fs::MetadataExt::uid(&match e.metadata() { Ok(m) => m, Err(_) => continue }) == me;
            if ours {
                let p = e.path();
                let gone = if p.is_dir() { fs::remove_dir_all(&p) } else { fs::remove_file(&p) };
                removed += gone.is_ok() as usize;
            }
        }
    }
    if !killed.is_empty() || removed > 0 {
        eprintln!(
            "midas: {} changed hands — stopped {} process(es) the previous holder left running{}, cleared {removed} item(s) from /tmp",
            cfg.node,
            killed.len(),
            if killed.is_empty() { String::new() } else { format!(" ({})", killed.join("; ")) },
        );
    }
    emit(cfg, "handover", json!({
        "previous": previous.trim(), "actor": owner, "killed": killed, "tmp_removed": removed,
        "bot_cleared": bot.then_some(true),
    }));
}

/// How many ssh sessions are open on this node: sshd's per-session processes
/// for `build` (`sshd: build@…`, or `sshd-session: build@…` in newer OpenSSH).
fn ssh_sessions() -> usize {
    crate::procs::ssh_sessions(&crate::procs::all(), "build")
}

/// A node on macOS is a whole virtual machine: its memory and load are the
/// machine's own, read from `sysctl` and `vm_stat` (there is no /proc or cgroup).
mod macos {
    use std::process::Command;

    fn sysctl(name: &str) -> Option<String> {
        let out = Command::new("sysctl").args(["-n", name]).output().ok().filter(|o| o.status.success())?;
        Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
    }

    /// `{ 1.52 1.40 1.31 }` → 1.52.
    pub fn load() -> Option<f64> {
        if !cfg!(target_os = "macos") {
            return None;
        }
        sysctl("vm.loadavg")?.trim_matches(['{', '}', ' ']).split_whitespace().next()?.parse().ok()
    }

    /// (in use, total) bytes: active, wired and compressed pages against the
    /// machine's memory.
    pub fn memory() -> Option<(u64, u64)> {
        if !cfg!(target_os = "macos") {
            return None;
        }
        let total: u64 = sysctl("hw.memsize")?.parse().ok()?;
        let out = Command::new("vm_stat").output().ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        let page: u64 = text.lines().next()?.split("page size of ").nth(1)?.split_whitespace().next()?.parse().ok()?;
        let pages = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).and_then(|v| v.trim().trim_end_matches('.').parse::<u64>().ok()).unwrap_or(0);
        let used = (pages("Pages active:") + pages("Pages wired down:") + pages("Pages occupied by compressor:")) * page;
        Some((used, total))
    }
}

const TARGET_SIZE: &str = "/work/.midas-target-size";

/// The build directory's size, for the warmer's 24 GB ceiling and the holder's
/// disk warning. Written to a file the reading picks up.
fn measure_target() {
    let target = Path::new(CHECKOUT).join("target");
    if !target.is_dir() {
        return;
    }
    // -k, not GNU's -b: the same on Linux and macOS nodes.
    if let Ok(out) = Command::new("du").args(["-sk", &target.to_string_lossy()]).output() {
        if let Some(kb) = String::from_utf8_lossy(&out.stdout).split_whitespace().next().and_then(|n| n.parse::<u64>().ok()) {
            let _ = fs::write(TARGET_SIZE, (kb * 1024).to_string());
        }
    }
}

/// Where a part of target/ goes on its way out: renamed there in one step, so a
/// build never sees it half deleted, then removed. On /work, beside target/.
const TRASH: &str = "/work/.midas-trash";

/// Over the ceiling the warmer keeps (`warm::ceiling`), the guard trims target/
/// itself, while no ssh session and no bot is on the node, held or not. The
/// warmer trims only a node nobody holds, and sessions hold them for hours: the
/// Macs and vps-1 sat over it an hour or more 73 times in 60 days, each one
/// mailed to the person, each one cleared by the warmer once the node was free
/// (2026-11-22). The order is the warmer's: incremental state, then the profile
/// or target triple built longest ago, and the whole of target/ last.
fn trim_target(cfg: &Config) {
    let _ = fs::remove_dir_all(TRASH); // what a trim cut short left
    let target = Path::new(CHECKOUT).join("target");
    let size = || fs::read_to_string(TARGET_SIZE).ok().and_then(|t| t.trim().parse::<u64>().ok());
    let Some(from) = size() else { return };
    // Once: what target/ drops is freed on /work, so their sum, and the ceiling, stay put.
    let limit = crate::warm::ceiling(from, crate::util::disk_space(Path::new("/work")).map(|d| d.0));
    let mut dropped = Vec::new();
    while size().is_some_and(|s| s > limit) {
        if ssh_sessions() > 0 || !crate::bot::reading().is_null() {
            break;
        }
        let Some(d) = next_to_drop(&target) else { break };
        if fs::rename(&d, TRASH).is_err() {
            break;
        }
        let _ = fs::remove_dir_all(TRASH);
        dropped.push(d.strip_prefix(CHECKOUT).unwrap_or(&d).to_string_lossy().to_string());
        if d == target {
            let _ = fs::write(TARGET_SIZE, "0");
        } else {
            measure_target();
        }
    }
    if !dropped.is_empty() {
        emit(cfg, "trim", json!({"actor": "guard", "dropped": dropped, "from": from, "to": size(), "ceiling": limit}));
    }
}

/// Where the other repositories' checkouts are (`flush.rs`): `/work/repos/owner/name`.
const REPOS: &str = "/work/repos";

/// A repository's build directory untouched this long is dropped when /work
/// runs short: its next build there is a cold one, which a session that comes
/// back to it after two days pays anyway.
const STALE_TARGET: Duration = Duration::from_secs(2 * 86400);

/// Below [`LOW_DISK`] free on /work, frees what costs least until
/// [`crate::warm::DISK_RESERVE`] is free or nothing cheap is left, on every
/// checkout of the node and not only the warm one: incremental
/// state first, then the build directories of repositories nobody built in
/// two days, oldest first; never the warm checkout's target/ beyond what
/// [`trim_target`] takes. The ceiling alone counts the warm checkout, and its
/// 24 GB floor holds however full the disk: on vps-1, whose /work is the VPS's
/// shared /data, the node trimmed itself back to 24 GB all afternoon while
/// /data stood at 0 free and every session's builds and git writes failed
/// (2026-11-26), with 10 GB of other repositories' builds never looked at.
fn free_up_disk(cfg: &Config) {
    let free = || crate::util::disk_space(Path::new("/work")).map_or(u64::MAX, |d| d.0);
    let from = free();
    // Only when short: a disk that holds other things too (vps-1's /data) may
    // never have the reserve free, and dropping incremental state every five
    // minutes there would make every build a slow one.
    if from >= LOW_DISK {
        return;
    }
    let mut targets = vec![Path::new(CHECKOUT).join("target")];
    targets.extend(repo_targets(Path::new(REPOS)));
    let mut candidates: Vec<PathBuf> = targets.iter().flat_map(|t| incremental_dirs(t)).collect();
    candidates.extend(stale_targets(Path::new(REPOS), std::time::SystemTime::now(), STALE_TARGET));
    let mut dropped = Vec::new();
    for d in candidates {
        if free() >= crate::warm::DISK_RESERVE {
            break;
        }
        // A build in progress keeps what it builds in.
        if ssh_sessions() > 0 || !crate::bot::reading().is_null() {
            break;
        }
        let _ = fs::remove_dir_all(TRASH);
        if fs::rename(&d, TRASH).is_err() {
            continue;
        }
        let _ = fs::remove_dir_all(TRASH);
        dropped.push(d.to_string_lossy().to_string());
    }
    if !dropped.is_empty() {
        measure_target();
        emit(cfg, "trim", json!({"actor": "guard", "reason": "disk", "dropped": dropped, "free_from": from, "free_to": free()}));
    }
}

/// The build directories of the checkouts under `repos` (`owner/name/target`).
fn repo_targets(repos: &Path) -> Vec<PathBuf> {
    let subdirs = |p: &Path| -> Vec<PathBuf> {
        fs::read_dir(p)
            .map(|r| r.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()).collect())
            .unwrap_or_default()
    };
    subdirs(repos)
        .iter()
        .flat_map(|owner| subdirs(owner))
        .map(|repo| repo.join("target"))
        .filter(|t| t.is_dir())
        .collect()
}

/// Every `incremental` directory of a build directory: `<profile>/incremental`
/// and `<triple>/<profile>/incremental`.
fn incremental_dirs(target: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let Ok(entries) = fs::read_dir(target) else {
        return out;
    };
    for e in entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) {
        let p = e.path();
        if p.join("incremental").is_dir() {
            out.push(p.join("incremental"));
        }
        if let Ok(inner) = fs::read_dir(&p) {
            for i in inner.flatten() {
                let q = i.path().join("incremental");
                if i.file_type().is_ok_and(|t| t.is_dir()) && q.is_dir() {
                    out.push(q);
                }
            }
        }
    }
    out.sort();
    out
}

/// The build directories under `repos` last written more than `age` before
/// `now`, oldest first. A build writes into its profile directory, so the
/// newest of target/ and its children is when it was last built.
fn stale_targets(repos: &Path, now: std::time::SystemTime, age: Duration) -> Vec<PathBuf> {
    let mtime = |p: &Path| fs::metadata(p).and_then(|m| m.modified()).ok();
    let mut found: Vec<(std::time::SystemTime, PathBuf)> = repo_targets(repos)
        .into_iter()
        .filter_map(|t| {
            let mut newest = mtime(&t)?;
            for e in fs::read_dir(&t).ok()?.flatten() {
                if let Some(m) = mtime(&e.path()) {
                    newest = newest.max(m);
                }
            }
            (now.duration_since(newest).ok()? > age).then_some((newest, t))
        })
        .collect();
    found.sort();
    found.into_iter().map(|(_, t)| t).collect()
}

/// What a trim drops next: incremental state, then the oldest of target/'s
/// other profiles and triples, then target/ itself.
fn next_to_drop(target: &Path) -> Option<std::path::PathBuf> {
    let incremental = target.join("debug/incremental");
    if incremental.is_dir() {
        return Some(incremental);
    }
    let oldest = fs::read_dir(target).ok()?.flatten()
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && e.file_name() != "debug")
        .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
        .min_by_key(|(t, _)| *t)
        .map(|(_, p)| p);
    oldest.or_else(|| target.is_dir().then(|| target.to_path_buf()))
}

/// Below this much free space on /work, sessions are warned.
const LOW_DISK: u64 = 10_000_000_000;

/// Regular files under `dir` (one level, plus one level of subdirectories)
/// modified since `since`, largest first: `(path, bytes)`.
fn new_files(dir: &str, since: std::time::SystemTime) -> Vec<(String, u64)> {
    let mut out = Vec::new();
    fn walk(p: &Path, depth: u8, out: &mut Vec<(String, u64)>, since: std::time::SystemTime) {
        let Ok(rd) = fs::read_dir(p) else { return };
        for e in rd.flatten() {
            let Ok(md) = e.metadata() else { continue };
            if md.is_dir() && depth == 0 {
                walk(&e.path(), 1, out, since);
            } else if md.is_file() && md.modified().is_ok_and(|m| m >= since) {
                out.push((e.path().to_string_lossy().to_string(), md.len()));
            }
        }
    }
    walk(Path::new(dir), 0, &mut out, since);
    out.sort_by(|a, b| b.1.cmp(&a.1));
    out
}

fn human(n: u64) -> String {
    match n {
        n if n >= 1 << 30 => format!("{:.1} GB", n as f64 / (1u64 << 30) as f64),
        n if n >= 1 << 20 => format!("{:.1} MB", n as f64 / (1u64 << 20) as f64),
        n if n >= 1 << 10 => format!("{} KB", n >> 10),
        n => format!("{n} B"),
    }
}

/// Tell the hub this node's two public keys: the one it fetches git with and
/// its sshd's host key. The hub accepts them only from this node's WireGuard
/// address, so registering needs no secret and nobody copies keys around. The
/// entrypoint runs it at every start (a set-up-again node has new keys).
pub fn register() -> Result<i32> {
    let cfg = config();
    let read = |p: &str| fs::read_to_string(p).map(|s| s.trim().to_string());
    let body = json!({
        "git_key": read("/work/.ssh-node/id_ed25519.pub")?,
        "host_key": read("/work/.ssh-host/ssh_host_ed25519_key.pub")?,
    });
    let (code, text) = hub::request(&cfg.hub, "POST", &format!("/v1/nodes/{}/register", cfg.node), Some(&body.to_string()))?;
    if code != 200 {
        anyhow::bail!("the hub refused the registration ({code}): {text}");
    }
    println!("midas node {}: registered with the hub", cfg.node);
    Ok(0)
}

/// This binary's platform as the hub names the midas it keeps for nodes:
/// `linux-x86_64`, `macos-aarch64`.
pub fn platform() -> String {
    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}

/// `os-arch`, in the words `platform` uses: what a path may be built from.
pub fn is_platform(p: &str) -> bool {
    p.split_once('-').is_some_and(|(os, arch)| {
        !os.is_empty() && !arch.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    })
}

/// The midas every session, sshd hook and the guard run — all as `build` —
/// and the one the hub replaces (`update`).
const INSTALLED: &str = "/usr/local/bin/midas";

/// `midas node update`, every few minutes, as the node's root: make the midas
/// sessions run the hub's build. Everything that runs as `build` here already
/// comes from the hub — the code every build compiles and runs, and who may
/// log in — so the hub's midas there gives a hub nothing new.
///
/// This command itself is never the hub's: the entrypoint runs it from the
/// owner's copy (`/usr/local/libexec/midas-owner`, from their `midas setup`),
/// and it runs what it downloads only as `build`. So the hub's code never runs
/// as the node's root, and a broken build from the hub cannot break the
/// updater that will take its fix. The machine's own protection — its
/// firewall, the node's user, the container or VM — never runs either (§3).
/// Only while nobody holds the node and nothing runs on it.
pub fn update() -> Result<i32> {
    let cfg = config();
    let platform = platform();
    let (code, body) = hub::request(&cfg.hub, "GET", &format!("/v1/nodes/{}/midas?platform={platform}", cfg.node), None)?;
    if code == 404 {
        return Ok(0); // a hub from before nodes followed it
    }
    if code != 200 {
        anyhow::bail!("the hub answered {code}: {body}");
    }
    let v: Value = serde_json::from_str(&body)?;
    let Some(want) = v["build"].as_str() else {
        return Ok(0); // nothing for this platform: sessions keep the midas they have
    };
    let exe = Path::new(INSTALLED);
    let have = version_as_build(exe);
    if have.as_deref() == Some(want) || v["held"] == true || !running_commands().is_empty() || ssh_sessions() > 0 {
        return Ok(0);
    }
    let tmp = exe.with_file_name(".midas.update");
    let _ = fs::remove_file(&tmp);
    hub::download(&cfg.hub, &format!("/v1/nodes/{}/midas/{platform}", cfg.node), &tmp)?;
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&tmp, fs::Permissions::from_mode(0o755))?;
    }
    // Whole, for this machine, and the build the hub said: it runs and says so.
    let says = version_as_build(&tmp);
    if says.as_deref() != Some(want) {
        let _ = fs::remove_file(&tmp);
        emit(&cfg, "node_update_failed", json!({"want": want, "got": says}));
        anyhow::bail!("the hub's midas for {platform} says {says:?}, not {want}; sessions keep {have:?}");
    }
    // Renamed over: a session running the old one keeps its file.
    fs::rename(&tmp, exe)?;
    emit(&cfg, "node_updated", json!({"from": have, "to": want}));
    println!("midas node {}: sessions run midas {want} (was {})", cfg.node, have.as_deref().unwrap_or("?"));
    // The guard (the heartbeat) runs the old one until it exits; its loop in
    // the entrypoint starts it again from the new file.
    let _ = Command::new("pkill").args(["-f", "midas node guard"]).status();
    Ok(0)
}

/// The build a midas binary says it is, asked as `build`: never as root, since
/// the binary may be the hub's.
fn version_as_build(bin: &Path) -> Option<String> {
    use std::os::unix::process::CommandExt as _;
    let id = |flag: &str| Command::new("id").args([flag, "build"]).output().ok()
        .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse::<u32>().ok());
    let (uid, gid) = (id("-u")?, id("-g")?);
    let out = Command::new(bin).arg("--version").uid(uid).gid(gid).env_clear().output().ok()?;
    let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
    out.status.success().then(|| text.strip_prefix("midas ").map(str::to_string)).flatten()
}

#[cfg(test)]
mod tests {
    #[test]
    fn a_build_or_a_test_is_told_from_a_look_at_the_checkout() {
        for c in ["cargo test -p x", "cd web && bun test", "RUST_LOG=debug cargo run", "time cargo build",
                  "timeout 600 cargo test 2>&1 | tail", "/usr/local/bin/cargo check", "./gradlew build", "env A=1 make"] {
            assert!(builds(c), "{c}");
        }
        for c in ["tail -f /tmp/log", "ls target", "cat Cargo.toml", "cd web", "git status", "ps aux | grep cargo"] {
            assert!(!builds(c), "{c}");
        }
    }

    use super::*;

    #[test]
    fn short_of_disk_the_guard_finds_incremental_state_and_cold_repositories() {
        let root = tempfile::tempdir().unwrap();
        let repos = root.path().join("repos");
        let mk = |p: &Path| fs::create_dir_all(p).unwrap();
        let mithril = repos.join("jeroen/mithril/target");
        let pinnacle = repos.join("jeroen/pinnacle/target");
        mk(&mithril.join("debug/incremental"));
        mk(&mithril.join("wasm32-unknown-unknown/debug/incremental"));
        mk(&mithril.join("release/deps"));
        mk(&pinnacle.join("aarch64-unknown-none/release/deps"));
        mk(&repos.join("jeroen/frits/src")); // no target/: not a candidate
        assert_eq!(repo_targets(&repos).len(), 2);
        assert_eq!(
            incremental_dirs(&mithril),
            vec![mithril.join("debug/incremental"), mithril.join("wasm32-unknown-unknown/debug/incremental")]
        );
        assert!(incremental_dirs(&pinnacle).is_empty());
        // Just built: nothing is stale. Three days on: both are, oldest first.
        let now = std::time::SystemTime::now();
        assert!(stale_targets(&repos, now, STALE_TARGET).is_empty());
        let later = now + Duration::from_secs(3 * 86400);
        assert_eq!(stale_targets(&repos, later, STALE_TARGET).len(), 2);
    }

    #[test]
    fn a_running_command_is_counted_until_its_session_is_gone() {
        let dir = std::env::temp_dir().join(format!("midas-running-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let mut sleeper = Command::new("sleep").arg("30").spawn().unwrap();
        fs::write(dir.join(sleeper.id().to_string()), "cargo test --workspace").unwrap();
        fs::write(dir.join(std::process::id().to_string()), "this very apply").unwrap();
        // A pid that cannot be alive: past the kernel's limit.
        fs::write(dir.join("2147483646"), "killed with its connection").unwrap();
        assert_eq!(running_in(&dir), vec!["cargo test --workspace"], "not its own session, not a dead one");
        assert!(!dir.join("2147483646").exists(), "a dead session's marker is cleared");
        let _ = sleeper.kill();
        let _ = sleeper.wait();
        assert!(running_in(&dir).is_empty());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_trim_drops_incremental_state_then_the_oldest_profile_then_target() {
        use super::next_to_drop;
        use std::fs;
        let dir = tempfile::tempdir().unwrap();
        let t = dir.path().join("target");
        for d in ["debug/incremental", "release", "aarch64-linux-android"] {
            fs::create_dir_all(t.join(d)).unwrap();
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(next_to_drop(&t), Some(t.join("debug/incremental")));
        fs::remove_dir_all(t.join("debug/incremental")).unwrap();
        assert_eq!(next_to_drop(&t), Some(t.join("release")), "built longest ago");
        fs::remove_dir_all(t.join("release")).unwrap();
        fs::remove_dir_all(t.join("aarch64-linux-android")).unwrap();
        assert_eq!(next_to_drop(&t), Some(t.clone()), "debug/ goes only with the whole of target/");
        fs::remove_dir_all(&t).unwrap();
        assert_eq!(next_to_drop(&t), None);
    }
}