garage44.eu/jeroen/midas

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

.. /src/registry.rs

raw

//! The workspace's state, and the rules that decide who gets a node. **The hub owns
//! this**: it lives in the hub's own directory (`$MIDAS_STATE`, by default
//! `/srv/midas/state`), the hub process and the hub's warmer are the only
//! things that open it, and everything else asks the hub over HTTP (`client`).
//!
//! It used to be a JSON file on the agent container's volume that three users
//! wrote under a cross-container `flock` — the agent, the hub through a bind
//! mount and a shared group, and root through sudo — and a third of `midas
//! check` was making sure that still worked. One writer needs none of that.
//!
//! Files in the state directory:
//! * `registry.json` — leases, waiters, each node's live flags (`enabled`,
//!   `drained`) and the landing queue; `registry.json.ok` one operation
//!   behind, to recover from.
//! * `nodes.json` — the node definitions. All of them: a node is data, added
//!   with `midas nodes add`, never code.
//! * `readings/<node>.json` — each node's latest heartbeat.
//! * `log/events-YYYY-MM-DD.jsonl` — the event log (`events`).

use std::fs::{self, File};
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use serde_json::{json, Map, Value};

use crate::events;
use crate::store;

/// 2 h: long enough for a cold build, short enough that an agent killed
/// mid-session frees its node. Every ssh to a node renews it.
pub const DEFAULT_TTL: i64 = 7200;
/// A lease whose node has had no ssh session open for this long is given back,
/// so a session that took a node and wandered off does not hold it for hours.
/// Nodes report their open sessions with every heartbeat, and an open one
/// renews the lease, so a long build is never cut short.
pub const IDLE_S: i64 = 1800;
/// The same, when somebody waits for the node: a third of the leases in the
/// week to 2026-10-25 ended only by sitting idle for [`IDLE_S`], while takes
/// gave up waiting. Its holder is nudged at five quiet minutes
/// (`collab::nudge_idle_holders`); five more and the node goes to the line.
/// Twenty until 2026-11-27: session leases were in use 54% of the time held,
/// and others waited 14 h in a month behind ones sitting idle (s647 held deck-1
/// 12 h with nothing running). The tree stays on the node, and `prefer_last`
/// sends its holder back there when it is free again.
pub const WAITED_IDLE_S: i64 = 600;
/// The same, when a deploy or a landing gate waits for the node: what waits has
/// landed, or holds the one turn to land that every session shares. sim and
/// atlas waited 14 minutes for a vps node a session held with nothing running
/// (2026-10-29). No ssh session open and no command for five minutes is not a
/// build cut short.
pub const DEPLOY_IDLE_S: i64 = 300;
/// A job lease (`midas run`) with nothing running on it, nobody waiting: kept
/// this long, so the next run of the same session finds its node warm with its
/// tree, and an `scp` of what the run wrote still reaches it.
pub const JOB_IDLE_S: i64 = 600;
/// The same, when somebody waits for the node: a job lease is held for one
/// command, so it goes as soon as that command has ended. The minute leaves
/// room for an `scp` straight after. Build leases were held nearly three times as
/// long as anything ran on them — the Macs 102 h, of which 38 h in use, in
/// the two weeks to 2026-11-14 — while sessions waited 25 h for them.
pub const JOB_WAITED_IDLE_S: i64 = 60;
/// How long a session's last node is remembered, to send its next run there.
pub const AFFINITY_S: i64 = 24 * 3600;
/// A claim naming one node that has waited this long takes another node on the
/// same machine when one is free: a second Mac VM is as fast and as able as the
/// first. Sessions waited 36 h for a named node in the month to 2026-11-27, 22 h
/// of it while its sibling was free ("Waarom wachten op mac-2; mac-1 is vrij").
pub const NAMED_FALLBACK_S: i64 = 300;

/// The hub's deploy builder (`deploy.rs`): first in every line for a node.
pub fn is_deploy(owner: &str) -> bool {
    owner.starts_with("deployer:")
}

/// A landing gate (`gate-<worktree>`, `skills/finish-branch/land`).
pub fn is_gate(owner: &str) -> bool {
    owner.starts_with("gate-")
}

/// Where a claimant stands in every line for a node: deploys, then landing
/// gates, then everyone else. A gate holds the landing turn every session
/// shares, so an ordinary build ahead of it holds up all of them: s530's
/// few-second gate waited 14 minutes behind sessions' builds (2026-10-31).
fn tier(owner: &str) -> u8 {
    if is_deploy(owner) { 0 } else if is_gate(owner) { 1 } else { 2 }
}

/// How long a waiter stays queued without asking again. Waiting clients ask
/// every 5 s, so two minutes of silence means it gave up.
pub const WAITER_TTL: i64 = 120;
/// A landing renews its turn every minute while it rebases, gates and pushes;
/// one silent for this long has died, and the next in line goes.
pub const LAND_TTL: i64 = 600;

/// The hub's state directory.
pub fn root() -> PathBuf {
    PathBuf::from(std::env::var("MIDAS_STATE").unwrap_or_else(|_| "/srv/midas/state".into()))
}

/// Is this process the hub (or its warmer) — where the state is?
pub fn is_hub() -> bool {
    std::env::var_os("MIDAS_STATE").is_some() || root().join("registry.json").exists()
}

pub fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

/// Fields a node's definition owns; the registry keeps its own live flags
/// (`enabled`, `drained`) beside them.
const DEFINITION_FIELDS: &[&str] = &[
    "machine", "address", "ssh_port", "gpu", "renderer", "host_key", "uuid",
];

fn nodes_file() -> PathBuf {
    root().join("nodes.json")
}

/// Every node midas knows, from `nodes.json`.
pub fn nodes() -> Vec<Value> {
    store::read(&nodes_file()).unwrap_or_default()
}

/// Change the node definitions under their own lock: a heartbeat noting where
/// a node reaches the hub and a node registering its keys arrive on threads
/// of their own. Taken after the registry's lock where both are held, never
/// before it.
fn edit_nodes<R>(f: impl FnOnce(&mut Vec<Value>) -> Result<R>) -> Result<R> {
    store::update(nodes_file(), f)
}

pub fn is_node(id: &str) -> bool {
    nodes().iter().any(|s| s["id"] == id)
}

/// The registry, locked for as long as this value lives: the hub's request
/// threads and the warmer take turns on it.
pub struct Locked {
    lock: Option<File>,
    root: PathBuf,
    pub state: Value,
    dirty: bool,
    /// Notes for holders whose node went back (`reap`), sent once the lock is
    /// let go: a note may wake a hosted session, which is no work to do under it.
    notices: Vec<(String, String)>,
}

impl Drop for Locked {
    fn drop(&mut self) {
        drop(self.lock.take());
        for (owner, text) in std::mem::take(&mut self.notices) {
            let _ = crate::collab::say("hub", &owner, &text, "lease");
        }
    }
}

impl Locked {
    pub fn open() -> Result<Self> {
        let root = root();
        let lock = store::lock(&root.join(".lock"))?;
        let state = read_state(&root)?;
        Ok(Self { lock: Some(lock), root, state, dirty: false, notices: Vec::new() })
    }

    pub fn mark(&mut self) {
        self.dirty = true;
    }

    pub fn commit(&mut self) -> Result<()> {
        if !self.dirty {
            return Ok(());
        }
        let text = serde_json::to_string_pretty(&self.state)?;
        // The copy to recover from is the state before this one, as a second name for the file
        // the rename below replaces: written out again, it cost a second write and fsync under
        // the lock at every renewal, and was this very state, not one behind.
        let (reg, ok) = (self.root.join("registry.json"), self.root.join("registry.json.ok"));
        if reg.exists() {
            let _ = fs::remove_file(&ok);
            let _ = fs::hard_link(&reg, &ok);
        }
        store::write_atomic(&reg, text.as_bytes(), store::PUBLIC)?;
        self.dirty = false;
        Ok(())
    }

    pub fn nodes(&self) -> &Vec<Value> {
        self.state["nodes"].as_array().expect("nodes is an array")
    }

    pub fn node(&self, id: &str) -> Option<&Value> {
        self.nodes().iter().find(|s| s["id"] == id)
    }

    pub fn node_mut(&mut self, id: &str) -> Option<&mut Value> {
        self.state["nodes"].as_array_mut().and_then(|v| v.iter_mut().find(|s| s["id"] == id))
    }

    pub fn leases(&self) -> &Map<String, Value> {
        self.state["leases"].as_object().expect("leases is an object")
    }

    pub fn leases_mut(&mut self) -> &mut Map<String, Value> {
        self.state["leases"].as_object_mut().expect("leases is an object")
    }

    pub fn waiters(&self) -> &Map<String, Value> {
        self.state["waiters"].as_object().expect("waiters is an object")
    }

    pub fn waiters_mut(&mut self) -> &mut Map<String, Value> {
        self.state["waiters"].as_object_mut().expect("waiters is an object")
    }

    pub fn held_by(&self, owner: &str) -> Option<String> {
        self.leases().iter().find(|(_, l)| l["owner"] == owner).map(|(sid, _)| sid.clone())
    }

    /// Drop leases nobody renewed and waiters who stopped asking, and log both:
    /// a lease lapsing under a working agent is the failure this system has been
    /// worst at.
    pub fn reap(&mut self) {
        let t = now();
        let lapsed: Vec<(String, &str, i64)> = self.leases().iter().filter_map(|(s, l)| {
            let limit = self.idle_limit(s, l, t);
            if expired(l, t) && may_lapse(s, l, t) {
                Some((s.clone(), "lease_lapsed", limit))
            } else if idle(s, l, t, limit) {
                Some((s.clone(), "lease_idle", limit))
            } else {
                None
            }
        }).collect();
        for (sid, kind, limit) in &lapsed {
            if let Some(l) = self.leases_mut().remove(sid) {
                events::emit(kind, json!({
                    "node": sid, "actor": l["owner"], "claimed_at": l["claimed_at"],
                    "renewed_at": l["renewed_at"], "last_command": l.get("last_command"),
                    "idle_limit_s": (*kind == "lease_idle").then_some(*limit),
                    "mode": (mode_of(&l) != Mode::Build).then_some(mode_of(&l).as_str()),
                }));
                // Said to the holder, or a loop of its keeps asking a node that
                // is somebody else's now, refused every time (485 times over a
                // few hours, 2026-10-19).
                // Not a job lease's end, which is its design rather than news:
                // its holder's next `midas run` takes a node by itself.
                let Some(owner) = l["owner"].as_str().filter(|o| !o.is_empty() && *o != "warmer" && mode_of(&l) != Mode::Job)
                    else { continue };
                let why = if *kind == "lease_idle" {
                    format!("nothing ran on it for {} minutes{}", limit / 60,
                            if *limit <= DEPLOY_IDLE_S { " while a deploy or a landing gate waited for it" }
                            else if *limit < IDLE_S { " while somebody waited for it" } else { "" })
                } else {
                    "nobody renewed its lease".to_string()
                };
                self.notices.push((owner.to_string(), format!(
                    "{sid} went back to the pool: {why}. Stop anything still polling it; `midas take` for a node again.")));
            }
        }
        let gone: Vec<String> = self.waiters().iter()
            .filter(|(_, w)| t - w["seen_at"].as_i64().unwrap_or(0) > WAITER_TTL)
            .map(|(o, _)| o.clone()).collect();
        for o in &gone {
            if let Some(w) = self.waiters_mut().remove(o) {
                events::emit("waiter_dropped", json!({"actor": o, "since": w["since"], "wanted": w.get("node").or(w.get("machine"))}));
            }
        }
        // A next turn (`reserve_next`) whose session stopped waiting for it:
        // the node would otherwise stay drained for nobody.
        let orphaned: Vec<(String, String)> = self.nodes().iter().filter_map(|n| {
            let f = n["drained"]["for"].as_str()?;
            let stale = t - n["drained"]["at"].as_i64().unwrap_or(0) > WAITER_TTL;
            (stale && !self.waiters().contains_key(f)).then(|| (n["id"].as_str().unwrap_or("").to_string(), f.to_string()))
        }).collect();
        for (id, f) in &orphaned {
            if let Some(o) = self.node_mut(id).and_then(Value::as_object_mut) {
                o.remove("drained");
            }
            events::emit("undrained", json!({"node": id, "actor": "hub", "why": format!("next turn lapsed: {f} stopped waiting")}));
        }
        if !lapsed.is_empty() || !gone.is_empty() || !orphaned.is_empty() {
            self.mark();
        }
        self.reap_landing(t);
    }

    /// How long `node` may sit unused before it goes back: [`WAITED_IDLE_S`]
    /// when a live waiter wants it and its holder has not said it needs it
    /// for longer (`midas intent … --minutes`), [`IDLE_S`] otherwise; a job
    /// lease's own two ([`JOB_WAITED_IDLE_S`], [`JOB_IDLE_S`]).
    fn idle_limit(&self, node: &str, lease: &Value, t: i64) -> i64 {
        let Some(n) = self.node(node) else { return IDLE_S };
        let waiting: Vec<&String> = self.waiters().iter()
            .filter(|(_, w)| t - w["seen_at"].as_i64().unwrap_or(0) <= WAITER_TTL && wants(w, n)).map(|(o, _)| o).collect();
        let promised = lease["intent_until"].as_i64().is_some_and(|u| u > t);
        if mode_of(lease) == Mode::Job {
            return if promised || waiting.is_empty() { JOB_IDLE_S } else { JOB_WAITED_IDLE_S };
        }
        if promised || waiting.is_empty() {
            IDLE_S
        } else if waiting.iter().any(|o| tier(o) < 2) {
            DEPLOY_IDLE_S
        } else {
            WAITED_IDLE_S
        }
    }

    fn landing(&self) -> &Value {
        &self.state["landing"]
    }

    fn landing_queue_mut(&mut self) -> &mut Map<String, Value> {
        self.state["landing"]["queue"].as_object_mut().expect("the landing queue is an object")
    }

    /// A landing whose holder stopped renewing, and places in line nobody is
    /// asking about any more.
    fn reap_landing(&mut self, t: i64) {
        let holder = self.landing()["holder"].clone();
        if holder.is_object() && t - holder["renewed_at"].as_i64().unwrap_or(0) > LAND_TTL {
            self.state["landing"]["holder"] = Value::Null;
            events::emit("landing_lapsed", json!({
                "actor": holder["owner"], "branch": holder["branch"], "step": holder.get("step"),
                "held_s": holder["granted_at"].as_i64().map(|g| t - g),
            }));
            self.mark();
        }
        let gone: Vec<String> = self.landing()["queue"].as_object().into_iter().flatten()
            .filter(|(_, w)| t - w["seen_at"].as_i64().unwrap_or(0) > WAITER_TTL)
            .map(|(o, _)| o.clone()).collect();
        for o in &gone {
            if let Some(w) = self.landing_queue_mut().remove(o) {
                events::emit("landing_gave_up", json!({"actor": o, "branch": w["branch"], "waited_s": w["since"].as_i64().map(|s| t - s)}));
            }
        }
        if !gone.is_empty() {
            self.mark();
        }
    }
}

/// No session open on the node now, no bot running for a bot lease, and
/// neither for `limit` ([`Locked::idle_limit`]). A node that does not report sessions (an older
/// build) is never idle by this rule. A bot lease counts from its holder's
/// last contact, not its last renewal: the heartbeat renewed it all the while
/// the bot ran.
///
/// Only on a heartbeat that is current, and counted from no earlier than the
/// hub began hearing the node without a gap: while the hub was down the node
/// still let its holder in (`node::holds`), and nothing of that reached the
/// hub — the old reading's "no sessions" says nothing about the outage.
fn idle(node: &str, lease: &Value, t: i64, limit: i64) -> bool {
    let Some(r) = reading(node) else { return false };
    let at = r["at"].as_i64().unwrap_or(0);
    if t - at > READING_GAP_S {
        return false;
    }
    let quiet_since = match mode_of(lease) {
        Mode::Build | Mode::Job => lease["renewed_at"].as_i64().unwrap_or(0),
        Mode::Bot => last_contact(lease),
    }.max(r["heard_since"].as_i64().unwrap_or(at));
    r["sessions"].as_u64() == Some(0) && !in_use(&r, lease) && t - quiet_since > limit
}

/// May a lease nobody renewed lapse? Yes on a current heartbeat that says it is
/// not in use, from a node the hub has heard without a gap for [`IDLE_S`], or
/// for a node that never reports one (an older build). Not on a stale one: the
/// hub back from an outage, or the warmer running while it is down (it opens
/// the state itself), would otherwise drop every lease at once and hand the
/// nodes on under their holders' running builds — and not straight after a
/// gap either, when the holder may have worked through it unheard. A node
/// silent for a day is gone, and its leases lapse.
fn may_lapse(node: &str, lease: &Value, t: i64) -> bool {
    let Some(r) = reading(node) else { return true };
    let at = r["at"].as_i64().unwrap_or(0);
    if t - at > SILENT_NODE_S {
        return true;
    }
    t - at <= READING_GAP_S && t - r["heard_since"].as_i64().unwrap_or(at) > IDLE_S && !in_use(&r, lease)
}

/// When the holder last did anything with the node: a command or an ssh
/// session it ran there, or a renewal it asked for. The heartbeat's own
/// renewals are not contact.
fn last_contact(lease: &Value) -> i64 {
    lease["last_active"].as_i64().max(lease["contact_at"].as_i64()).unwrap_or(0)
}

/// What a lease is for. **Build** is every lease there was before bot mode, and
/// what a lease that does not say reads as. **Bot**: the holder runs a
/// long-lived program on the node (`midas bot`) and talks to it over ssh, so
/// the lease is in use while that program runs, with no session open — for as
/// long as the holder keeps talking to it. **Job**: held for one command
/// (`midas run`), and given back a minute after it ends when somebody waits
/// ([`JOB_WAITED_IDLE_S`]), ten when nobody does ([`JOB_IDLE_S`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    Build,
    Bot,
    Job,
}

impl Mode {
    pub fn as_str(self) -> &'static str {
        match self {
            Mode::Build => "build",
            Mode::Bot => "bot",
            Mode::Job => "job",
        }
    }

    /// `None` (absent) is build; anything but the three names is refused.
    pub fn parse(s: Option<&str>) -> Result<Mode> {
        match s {
            None | Some("build") => Ok(Mode::Build),
            Some("bot") => Ok(Mode::Bot),
            Some("job") => Ok(Mode::Job),
            Some(other) => bail!("a lease's mode is build, bot or job, not {other:?}"),
        }
    }
}

/// A lease's mode; one written before modes existed is a build lease.
pub fn mode_of(lease: &Value) -> Mode {
    Mode::parse(lease["mode"].as_str()).unwrap_or(Mode::Build)
}

/// Does this heartbeat say the lease is in use? An open ssh session always
/// does; a running bot does for a bot lease whose holder has been in touch
/// within [`IDLE_S`] — a bot whose session had ended renewed its lease for
/// hours with nobody driving it (mac-2, 2026-10-17). A build lease's node
/// stops a bot it finds (`midas node guard`), so a bot there keeps nothing alive.
pub fn in_use(reading: &Value, lease: &Value) -> bool {
    has_session(reading)
        || (mode_of(lease) == Mode::Bot && reading["bot"]["running"] == true
            && now() - last_contact(lease) <= IDLE_S)
}

fn has_session(reading: &Value) -> bool {
    reading["sessions"].as_u64().is_some_and(|n| n > 0)
}

/// The heartbeat's renewal: a node in use keeps its lease, as a session
/// renewing it would, and an open session counts as the holder's contact (one
/// can outlast [`IDLE_S`], waiting on a bot). Returns whether it did.
pub fn renew_if_in_use(node: &str, reading: &Value) -> Result<bool> {
    let mut reg = Locked::open()?;
    reg.reap();
    let Some(l) = reg.leases_mut().get_mut(node) else { return Ok(false) };
    if !in_use(reading, l) {
        return Ok(false);
    }
    let t = now();
    l["renewed_at"] = json!(t);
    if has_session(reading) {
        l["contact_at"] = json!(t);
    }
    reg.mark();
    reg.commit()?;
    Ok(true)
}

fn expired(lease: &Value, t: i64) -> bool {
    t - lease["renewed_at"].as_i64().unwrap_or(0) > lease["ttl"].as_i64().unwrap_or(DEFAULT_TTL)
}

fn read_state(root: &Path) -> Result<Value> {
    let reg = root.join("registry.json");
    let mut state = None;
    for path in [reg.clone(), root.join("registry.json.ok")] {
        match fs::read_to_string(&path) {
            Ok(t) => if let Ok(v) = serde_json::from_str::<Value>(&t) {
                if path != reg {
                    events::emit("error", json!({"what": "registry unreadable; recovered the last good copy"}));
                }
                state = Some(v);
                break;
            },
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            // Out of descriptors, say: taken for no registry, the next commit wrote an empty one
            // over every lease and line. Refused instead, and asked again.
            Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
        }
    }
    Ok(normalise(state.unwrap_or_else(|| json!({}))))
}

/// The nodes are the node definitions, each with the registry's live flags kept.
fn normalise(mut state: Value) -> Value {
    if !state.is_object() {
        state = json!({});
    }
    let defs = nodes();
    let old: Vec<Value> = state["nodes"].as_array().cloned().unwrap_or_default();
    let nodes: Vec<Value> = defs.iter().map(|d| {
        let mut s = old.iter().find(|o| o["id"] == d["id"]).cloned()
            .unwrap_or_else(|| json!({"id": d["id"], "enabled": false}));
        for k in DEFINITION_FIELDS {
            match d.get(*k) {
                Some(v) => s[*k] = v.clone(),
                None => { if let Some(o) = s.as_object_mut() { o.remove(*k); } }
            }
        }
        s
    }).collect();
    let ids: Vec<Value> = defs.iter().map(|d| d["id"].clone()).collect();
    let obj = state.as_object_mut().unwrap();
    obj.insert("nodes".into(), Value::Array(nodes));
    obj.entry("leases").or_insert_with(|| json!({}));
    obj.entry("waiters").or_insert_with(|| json!({}));
    obj.entry("last_node").or_insert_with(|| json!({}));
    let landing = obj.entry("landing").or_insert_with(|| json!({}));
    if !landing.is_object() {
        *landing = json!({});
    }
    let landing = landing.as_object_mut().unwrap();
    landing.entry("holder").or_insert(Value::Null);
    if !landing.get("queue").is_some_and(Value::is_object) {
        landing.insert("queue".into(), json!({}));
    }
    if let Some(l) = obj.get_mut("leases").and_then(Value::as_object_mut) {
        l.retain(|sid, _| ids.iter().any(|i| i == sid.as_str()));
    }
    state
}

/// Does a host filter take this node? `any` takes all, `gpu` every node with a
/// GPU, anything else names a host group — or one node: `midas run mac-1`
/// once queued for a machine called mac-1, which no node is on, and waited
/// three hours while mac-1 stood free.
pub fn machine_matches(host: &str, node: &Value) -> bool {
    match host {
        "any" => true,
        "gpu" => node["gpu"] == true,
        h => node["machine"] == h || node["id"] == h,
    }
}

pub fn wants(waiter: &Value, node: &Value) -> bool {
    machine_matches(waiter["machine"].as_str().unwrap_or("any"), node)
        && (waiter["node"].is_null() || waiter["node"] == node["id"])
}

/// Waiters ahead of `owner` for this node: those of an earlier [`tier`], then
/// those of its own that asked before it — a deploy is ahead of every gate and
/// session, a gate ahead of every session. A claimant that is not queued (the
/// warmer) is behind all of its tier.
fn ahead_of(reg: &Locked, owner: &str, node: &Value) -> Vec<String> {
    let since = reg.waiters().get(owner).and_then(|w| w["since"].as_i64()).unwrap_or(i64::MAX);
    let mine = tier(owner);
    let mut v: Vec<(u8, i64, String)> = reg.waiters().iter()
        .filter(|(o, w)| {
            let theirs = tier(o);
            o.as_str() != owner && wants(w, node) && (theirs < mine || theirs == mine && w["since"].as_i64().unwrap_or(0) < since)
        })
        .map(|(o, w)| (tier(o), w["since"].as_i64().unwrap_or(0), o.clone()))
        .collect();
    v.sort();
    v.into_iter().map(|(_, _, o)| o).collect()
}

/// Order free nodes fastest first: for one kind of command (`command`, as a
/// claim gives it: the gate's whole command line, which is shortened here as
/// the build history records it, `builds::shape`), by the median of its
/// successful runs on the node over the last 30 days, or on the node's machine
/// when the node has none (a second Mac VM is as fast as the first); a node
/// that never ran it, by the median over all nodes scaled by its general build
/// speed — or a fast node new to a command would lose to every slow one that
/// ran it once. For a claim naming no command, by general build speed alone.
/// Nodes with no measurement go after those with one, and a GPU node after a
/// node as fast without one. Until 2026-11-27 the GPU went first in the key,
/// before speed: once the Macs were flagged GPU nodes (11-12) every take naming
/// no node went to the CPU node four times slower — 87 of 175 session leases
/// while a Mac was free, and Cartopolis gates of 905 s there against 214 s. What
/// needs a GPU is kept its node by the line instead: a free node somebody waits
/// for is "queued behind" them (`ahead_of`). The sort is stable, so ties keep
/// the listed order.
pub fn rank_by_speed(free: &mut [Value], command: Option<&str>) {
    let m = command.map(|c| crate::builds::medians(&crate::builds::shape(c), 30 * 86400)).unwrap_or_default();
    // Without a kind of command, or with one never run on these nodes: how
    // fast each is at building in general (`builds::speed_factors`).
    let (gen_node, gen_machine) = crate::builds::speed_factors(30 * 86400);
    let general = |n: &Value| {
        n["id"].as_str().and_then(|id| gen_node.get(id))
            .or_else(|| n["machine"].as_str().and_then(|m| gen_machine.get(m))).copied()
    };
    let estimate = |n: &Value| {
        n["id"].as_str().and_then(|id| m.by_node.get(id))
            .or_else(|| n["machine"].as_str().and_then(|k| m.by_machine.get(k)))
            .map(|s| *s as f64)
            .or_else(|| Some(m.all? as f64 * general(n)?))
    };
    free.sort_by(|a, b| {
        let key = |n: &Value| (estimate(n).is_none(), general(n).is_none(), n["gpu"] == true);
        let (ka, kb) = (key(a), key(b));
        ka.0.cmp(&kb.0)
            .then_with(|| estimate(a).unwrap_or(0.0).total_cmp(&estimate(b).unwrap_or(0.0)))
            .then(ka.1.cmp(&kb.1))
            .then_with(|| general(a).unwrap_or(1.0).total_cmp(&general(b).unwrap_or(1.0)))
            .then(ka.2.cmp(&kb.2))
    });
}

/// Of free nodes ranked fastest first, put the one `owner` held last first
/// when nobody has held it since and it is on the fastest one's machine — as
/// fast, and still at the owner's tree, so a run rebuilds only what changed
/// since its last one rather than everything between its branch and another's.
/// A run takes a node per command, and two Mac VMs tie on speed: without this,
/// each run could land on the node another session left.
pub fn prefer_last(free: &mut [Value], owner: &str, last: &Map<String, Value>, t: i64) {
    let Some(mine) = last.get(owner) else { return };
    let (Some(id), at) = (mine["node"].as_str(), mine["at"].as_i64().unwrap_or(0)) else { return };
    let since_taken = last.iter().any(|(o, l)| o != owner && l["node"] == id && l["at"].as_i64().unwrap_or(0) > at);
    if t - at > AFFINITY_S || since_taken {
        return;
    }
    let Some(first) = free.first().map(|n| n["machine"].clone()) else { return };
    if let Some(i) = free.iter().position(|n| n["id"] == id && n["machine"] == first) {
        free[..=i].rotate_right(1);
    }
}

/// A free node of `machine` faster at `command` than `than` (a node the asker
/// holds), when one is: the landing gate's question before it gates on the
/// node its session holds. 40% of Cartopolis gates ran on the CPU node, a
/// median 905 s against 214 s on a Mac, because the session held it while a
/// Mac sat free (2026-10-28 to 11-27). Nobody waiting for a node ahead of
/// `owner` is passed over.
pub fn faster_free(owner: &str, machine: &str, than: &str, command: Option<&str>) -> Result<Option<String>> {
    let reg = Locked::open()?;
    let Some(held) = reg.node(than).cloned() else { return Ok(None) };
    let mut v: Vec<Value> = reg.nodes().iter()
        .filter(|s| machine_matches(machine, s) && s["enabled"].as_bool().unwrap_or(false) && !s["drained"].is_object()
            && !reg.leases().contains_key(s["id"].as_str().unwrap_or("?")) && ahead_of(&reg, owner, s).is_empty())
        .cloned().collect();
    v.push(held);
    rank_by_speed(&mut v, command);
    Ok(v.first().and_then(|n| n["id"].as_str()).filter(|id| *id != than).map(str::to_string))
}

/// A request for a node.
pub struct Claim {
    pub owner: String,
    pub machine: String,
    pub node: Option<String>,
    pub branch: Option<String>,
    pub purpose: Option<String>,
    pub ttl: i64,
    /// Keep a place in line when nothing is free.
    pub queue: bool,
    pub mode: Mode,
    /// Of the free nodes, take the one that has run this command (a build
    /// history shape, `builds::shape`) fastest, instead of the first listed.
    pub rank: Option<String>,
}

/// Grant a node (`Ok(node)`), or say why not (`Err(details)`). A holder asking
/// again gets its own back — asking for a bot, as a bot lease: building on a
/// node and then running a bot there is one lease. Never the other way: a
/// `take` from a bot's holder must not stop its bot.
pub fn claim(c: &Claim) -> Result<std::result::Result<Value, Value>> {
    let mut reg = Locked::open()?;
    reg.reap();
    if let Some(sid) = reg.held_by(&c.owner) {
        let l = reg.leases_mut().get_mut(&sid).unwrap();
        l["renewed_at"] = json!(now());
        // Up only: a job lease taken for building is a build lease, either
        // taken for a bot a bot lease; a `run` leaves the lease it finds.
        let was = mode_of(l);
        let became = match (was, c.mode) {
            (Mode::Build | Mode::Job, Mode::Bot) => Some(Mode::Bot),
            (Mode::Job, Mode::Build) => Some(Mode::Build),
            _ => None,
        };
        if let Some(m) = became {
            l["mode"] = json!(m.as_str());
            if let Some(p) = &c.purpose {
                l["purpose"] = json!(p);
            }
        }
        reg.mark();
        reg.commit()?;
        if let Some(m) = became {
            events::emit("lease_mode", json!({"node": sid, "actor": c.owner, "mode": m.as_str(), "purpose": c.purpose}));
        }
        return Ok(Ok(reg.node(&sid).cloned().unwrap_or_default()));
    }
    let mut passed: Vec<Value> = Vec::new();
    let mut free: Vec<Value> = Vec::new();
    // A named node waited for long enough: its machine's other nodes too
    // ([`NAMED_FALLBACK_S`]). Not for a bot, which is set up on the node it
    // names, nor while a node is drained for this claimant's next turn.
    let waited = reg.waiters().get(&c.owner).and_then(|w| w["since"].as_i64()).map_or(0, |s| now() - s);
    let next_turn_kept = reg.nodes().iter().any(|s| s["drained"]["for"] == c.owner.as_str());
    let sibling_machine = c.node.as_deref()
        .filter(|_| c.mode != Mode::Bot && waited >= NAMED_FALLBACK_S && !next_turn_kept)
        .and_then(|w| reg.node(w)).and_then(|s| s["machine"].as_str()).map(str::to_string);
    for s in reg.nodes().clone() {
        let id = s["id"].as_str().unwrap_or("?").to_string();
        let named = c.node.as_deref().is_none_or(|w| w == id);
        let sibling = !named && sibling_machine.as_deref().is_some_and(|m| s["machine"] == m);
        if !machine_matches(&c.machine, &s) || !(named || sibling) {
            continue;
        }
        // Drained for this claimant (`reserve_next`): its turn, ahead of the line.
        let mine_next = s["drained"]["for"] == c.owner.as_str();
        let why = if !s["enabled"].as_bool().unwrap_or(false) {
            Some(json!({"node": id, "why": "offline"}))
        } else if s["drained"].is_object() && !mine_next {
            Some(json!({"node": id, "why": "drained", "reason": s["drained"]["why"], "for": s["drained"]["for"]}))
        } else if let Some(l) = reg.leases().get(&id) {
            Some(json!({"node": id, "why": "held", "holder": l["owner"]}))
        } else if mine_next {
            None
        } else {
            let ahead = ahead_of(&reg, &c.owner, &s);
            (!ahead.is_empty()).then(|| json!({"node": id, "why": "queued behind", "waiters": ahead}))
        };
        match why {
            // A sibling not free is not what the claim waits for.
            Some(_) if sibling => {}
            Some(w) => passed.push(w),
            None => free.push(s),
        }
    }
    // The fastest free node first: at this kind of command when the claim
    // names one, at building in general when it does not.
    if free.len() > 1 {
        rank_by_speed(&mut free, c.rank.as_deref());
        prefer_last(&mut free, &c.owner, reg.state["last_node"].as_object().unwrap_or(&Map::new()), now());
        // The node named, when it came free too.
        if let Some(i) = c.node.as_deref().and_then(|w| free.iter().position(|n| n["id"] == w)) {
            free[..=i].rotate_right(1);
        }
    }
    if let Some(s) = free.into_iter().next() {
        let id = s["id"].as_str().unwrap_or("?").to_string();
        let t = now();
        let mut lease = json!({"owner": c.owner, "branch": c.branch, "claimed_at": t, "renewed_at": t, "ttl": c.ttl,
                               "last_active": t, "mode": c.mode.as_str()});
        if let Some(p) = &c.purpose {
            lease["purpose"] = json!(p);
        }
        reg.leases_mut().insert(id.clone(), lease);
        if let Some(m) = reg.state["last_node"].as_object_mut() {
            m.retain(|_, l| t - l["at"].as_i64().unwrap_or(0) <= AFFINITY_S);
            m.insert(c.owner.clone(), json!({"node": id, "at": t}));
        }
        // A next turn is used up by taking it.
        let next_turn = s["drained"]["for"] == c.owner.as_str();
        if next_turn {
            if let Some(o) = reg.node_mut(&id).and_then(Value::as_object_mut) {
                o.remove("drained");
            }
        }
        let waited = reg.waiters_mut().remove(&c.owner);
        reg.mark();
        reg.commit()?;
        events::emit("claim", json!({
            "node": id, "actor": c.owner, "purpose": c.purpose, "branch": c.branch,
            "mode": (c.mode == Mode::Bot).then_some("bot"),
            "waited_s": waited.and_then(|w| w["since"].as_i64()).map(|s| now() - s),
            "ranked_by": c.rank,
            "instead_of": c.node.as_deref().filter(|w| *w != id),
            "next_turn": next_turn.then_some(true),
        }));
        return Ok(Ok(s));
    }
    let mut fresh = false;
    if c.queue {
        let t = now();
        fresh = !reg.waiters().contains_key(&c.owner);
        let w = reg.waiters_mut().entry(c.owner.clone()).or_insert_with(|| json!({"since": t}));
        w["seen_at"] = json!(t);
        w["machine"] = json!(c.machine);
        w["node"] = c.node.as_ref().map_or(Value::Null, |s| json!(s));
        w["mode"] = json!(c.mode.as_str());
        w["rank"] = c.rank.as_ref().map_or(Value::Null, |r| json!(r));
        if let Some(p) = &c.purpose {
            w["purpose"] = json!(p);
        }
        reg.mark();
        reg.commit()?;
    }
    // A waiting client asks every 5 s; log the first refusal of a wait, and
    // every refusal of a claimant that does not queue.
    if !c.queue || fresh {
        events::emit(if fresh { "queued" } else { "refused" }, json!({
            "actor": c.owner, "machine": c.machine, "wanted": c.node, "purpose": c.purpose, "passed_over": passed,
        }));
    }
    let position = if c.queue { position_in(&reg, &c.owner) } else { String::new() };
    Ok(Err(json!({"passed_over": passed, "position": position})))
}

pub fn release(owner: &str, node: Option<&str>, force: bool) -> Result<Option<String>> {
    let mut reg = Locked::open()?;
    let found = reg.leases().iter()
        .find(|(sid, l)| (l["owner"] == owner && node.is_none_or(|s| s == sid.as_str())) || (force && node == Some(sid.as_str())))
        .map(|(sid, l)| (sid.clone(), l.clone()));
    let Some((sid, l)) = found else { return Ok(None) };
    reg.leases_mut().remove(&sid);
    reg.mark();
    reg.commit()?;
    events::emit(if l["owner"] != owner { "force_release" } else { "release" }, json!({
        "node": sid, "actor": owner, "holder": l["owner"],
        "held_s": l["claimed_at"].as_i64().map(|c| now() - c), "last_command": l.get("last_command"),
    }));
    Ok(Some(sid))
}

/// Keep a lease alive, found by owner or by node; with a command, also record
/// what its holder is doing.
pub fn renew(owner: Option<&str>, node: Option<&str>, command: Option<&str>) -> Result<Option<String>> {
    let mut reg = Locked::open()?;
    reg.reap();
    let sid = match (owner, node) {
        (_, Some(s)) if reg.leases().contains_key(s) => s.to_string(),
        (Some(o), None) => match reg.held_by(o) { Some(s) => s, None => return Ok(None) },
        _ => return Ok(None),
    };
    let l = reg.leases_mut().get_mut(&sid).unwrap();
    l["renewed_at"] = json!(now());
    if owner.is_some() {
        // The holder asking is contact (`last_contact`), with or without a command.
        l["contact_at"] = json!(now());
    }
    if let Some(c) = command {
        l["last_active"] = json!(now());
        l["last_command"] = json!(crate::util::clip_words(c, 100));
    }
    reg.mark();
    reg.commit()?;
    Ok(Some(sid))
}


/// What the holder says it is doing with its node and for how long, so the
/// sessions waiting for it can plan (`midas intent`). `None` clears it.
pub fn set_intent(owner: &str, text: Option<&str>, minutes: Option<i64>) -> Result<Option<String>> {
    let mut reg = Locked::open()?;
    let Some(sid) = reg.held_by(owner) else { return Ok(None) };
    let l = reg.leases_mut().get_mut(&sid).unwrap();
    match text.map(str::trim).filter(|t| !t.is_empty()) {
        Some(t) => {
            l["intent"] = json!(t.chars().take(200).collect::<String>());
            l["intent_until"] = minutes.map_or(Value::Null, |m| json!(now() + m * 60));
        }
        None => {
            if let Some(o) = l.as_object_mut() {
                o.remove("intent");
                o.remove("intent_until");
            }
        }
    }
    reg.mark();
    reg.commit()?;
    events::emit("intent", json!({"node": sid, "actor": owner, "intent": text, "minutes": minutes}));
    Ok(Some(sid))
}

/// Give the node back when the holder's current ssh session on it ends, or at
/// once if none is open (`midas yield`); `on: false` takes that back.
pub fn set_yield(owner: &str, on: bool) -> Result<Option<(String, bool)>> {
    let mut reg = Locked::open()?;
    let Some(sid) = reg.held_by(owner) else { return Ok(None) };
    let idle = reading(&sid).is_some_and(|r| r["sessions"].as_u64() == Some(0));
    if on && idle {
        drop(reg);
        release(owner, Some(&sid), false)?;
        return Ok(Some((sid, true)));
    }
    let l = reg.leases_mut().get_mut(&sid).unwrap();
    l["yield"] = json!(on);
    reg.mark();
    reg.commit()?;
    events::emit("yield", json!({"node": sid, "actor": owner, "on": on}));
    Ok(Some((sid, false)))
}

/// An ssh session on `node` closed: if its holder said `midas yield`, the node
/// goes back now. The holder hears it with its next command.
pub fn session_closed_on(node: &str) -> Result<()> {
    let owner = {
        let reg = Locked::open()?;
        match reg.leases().get(node) {
            Some(l) if l["yield"] == true => l["owner"].as_str().unwrap_or("").to_string(),
            _ => return Ok(()),
        }
    };
    release(&owner, Some(node), false)?;
    crate::collab::say("hub", &owner, &format!("{node} went back to the pool after your build, as you asked (`midas yield`)."), "yield").map(drop)
}

pub fn unqueue(owner: &str) -> Result<()> {
    let mut reg = Locked::open()?;
    if let Some(w) = reg.waiters_mut().remove(owner) {
        reg.mark();
        reg.commit()?;
        events::emit("gave_up", json!({"actor": owner, "waited_s": w["since"].as_i64().map(|s| now() - s)}));
    }
    Ok(())
}

// ── The landing queue ────────────────────────────────────────────────────────
//
// Landing a branch on the warm branch is rebase, gate, fast-forward push, and
// the push only succeeds if nothing else landed since the rebase. Two landings
// at once means the second one's gate tested a base that is gone by the time
// it pushes: it is rerun from the top, a whole gate thrown away. Measured on
// the cartopolis workspace in the week to 2026-10-17: at least six green gates
// were rerun that way, because a landing rebased, then waited ~15 minutes for
// a node while the one ahead of it landed.
//
// So a landing takes a turn here before it rebases, and keeps it until its
// push is done: one landing at a time, first come first served, and a landing
// in progress is never overtaken. Its node is a separate lease, taken inside
// the turn; the turn is not a node.

/// Ask for the landing turn, or keep a place in line for it. `Ok` with the turn
/// when it is this owner's (asking again while holding it renews it), `Err`
/// with where it stands otherwise.
pub fn land_claim(owner: &str, branch: Option<&str>, purpose: Option<&str>) -> Result<std::result::Result<Value, Value>> {
    let mut reg = Locked::open()?;
    reg.reap();
    let t = now();
    if reg.landing()["holder"]["owner"] == owner {
        reg.state["landing"]["holder"]["renewed_at"] = json!(t);
        reg.mark();
        reg.commit()?;
        return Ok(Ok(reg.landing()["holder"].clone()));
    }
    let fresh = !reg.landing()["queue"].as_object().is_some_and(|q| q.contains_key(owner));
    let w = reg.landing_queue_mut().entry(owner.to_string()).or_insert_with(|| json!({"since": t}));
    w["seen_at"] = json!(t);
    w["branch"] = json!(branch);
    w["purpose"] = json!(purpose);
    reg.mark();
    let first = landing_line(&reg).first().cloned();
    if reg.landing()["holder"].is_null() && first.as_deref() == Some(owner) {
        let w = reg.landing_queue_mut().remove(owner).unwrap_or_default();
        let holder = json!({
            "owner": owner, "branch": branch, "purpose": purpose,
            "queued_at": w["since"], "granted_at": t, "renewed_at": t,
        });
        reg.state["landing"]["holder"] = holder.clone();
        reg.commit()?;
        events::emit("landing_granted", json!({
            "actor": owner, "branch": branch, "waited_s": w["since"].as_i64().map(|s| t - s),
        }));
        return Ok(Ok(holder));
    }
    reg.commit()?;
    if fresh {
        events::emit("landing_queued", json!({"actor": owner, "branch": branch, "holder": reg.landing()["holder"]["owner"]}));
    }
    Ok(Err(json!({"position": landing_position(&reg, owner), "holder": reg.landing()["holder"]})))
}

/// The landing queue's owners, first in line first.
fn landing_line(reg: &Locked) -> Vec<String> {
    let mut v: Vec<(i64, String)> = reg.landing()["queue"].as_object().into_iter().flatten()
        .map(|(o, w)| (w["since"].as_i64().unwrap_or(0), o.clone())).collect();
    v.sort();
    v.into_iter().map(|(_, o)| o).collect()
}

fn landing_position(reg: &Locked, owner: &str) -> String {
    let ahead = landing_line(reg).iter().take_while(|o| o.as_str() != owner).count();
    let place = if ahead == 0 { "next to land".to_string() } else { format!("{} in line to land", ordinal(ahead + 1)) };
    let h = &reg.landing()["holder"];
    if h.is_object() {
        let step = h["step"].as_str().map(|s| format!(", {s}")).unwrap_or_default();
        format!("{place}; {} is landing {} ({}m{step})", h["owner"].as_str().unwrap_or("?"),
            h["branch"].as_str().unwrap_or("a detached HEAD"), (now() - h["granted_at"].as_i64().unwrap_or(now())) / 60)
    } else {
        place
    }
}

/// Keep the landing turn, and say what it is doing (`midas status` shows it).
pub fn land_renew(owner: &str, step: Option<&str>) -> Result<bool> {
    let mut reg = Locked::open()?;
    reg.reap();
    if reg.landing()["holder"]["owner"] != owner {
        return Ok(false);
    }
    reg.state["landing"]["holder"]["renewed_at"] = json!(now());
    if let Some(s) = step {
        reg.state["landing"]["holder"]["step"] = json!(s.chars().take(100).collect::<String>());
    }
    reg.mark();
    reg.commit()?;
    Ok(true)
}

/// Give the turn back, or a place in line. `outcome` is what became of it —
/// landed, failed, abandoned — for the log.
pub fn land_release(owner: &str, outcome: Option<&str>, sha: Option<&str>) -> Result<bool> {
    let mut reg = Locked::open()?;
    let t = now();
    let h = reg.landing()["holder"].clone();
    if h["owner"] == owner {
        reg.state["landing"]["holder"] = Value::Null;
        reg.mark();
        reg.commit()?;
        events::emit("landing_done", json!({
            "actor": owner, "branch": h["branch"], "outcome": outcome, "sha": sha,
            "held_s": h["granted_at"].as_i64().map(|g| t - g),
            "waited_s": h["queued_at"].as_i64().zip(h["granted_at"].as_i64()).map(|(q, g)| g - q),
        }));
        return Ok(true);
    }
    if let Some(w) = reg.landing_queue_mut().remove(owner) {
        reg.mark();
        reg.commit()?;
        events::emit("landing_gave_up", json!({"actor": owner, "branch": w["branch"], "waited_s": w["since"].as_i64().map(|s| t - s)}));
        return Ok(true);
    }
    Ok(false)
}

/// The session holding the turn to land, if one does: a hosted repository's
/// pre-receive hook moves main only for it (`hosted::may_push`).
pub fn land_holder() -> Option<String> {
    let reg = Locked::open().ok()?;
    reg.landing()["holder"]["owner"].as_str().map(str::to_string)
}

/// The git server said a branch moved (its post-receive hook, through the hub).
/// Kept beside the queue, so `status` can say what the warm branch is now.
pub fn note_push(repo: &str, refname: &str, old: &str, new: &str) -> Result<()> {
    let mut reg = Locked::open()?;
    reg.state["landing"]["pushed"][refname] = json!({"repo": repo, "sha": new, "at": now()});
    reg.mark();
    reg.commit()?;
    let holder = reg.landing()["holder"]["owner"].clone();
    events::emit("pushed", json!({"repo": repo, "ref": refname, "old": old, "new": new, "landing": holder}));
    Ok(())
}

/// The hub's heartbeat watch flips this; nothing else should.
pub fn set_online(node: &str, on: bool, why: &str) -> Result<()> {
    let mut reg = Locked::open()?;
    let Some(s) = reg.node_mut(node) else { bail!("no such node: {node}") };
    if s["enabled"].as_bool().unwrap_or(false) == on {
        return Ok(());
    }
    s["enabled"] = json!(on);
    reg.mark();
    reg.commit()?;
    events::emit(if on { "node_online" } else { "node_offline" }, json!({"node": node, "why": why}));
    Ok(())
}

/// Out of the pool on purpose, with a reason, until undrained. A current lease
/// runs on; nobody new gets the node, the warmer included.
pub fn drain(node: &str, why: Option<&str>, by: &str) -> Result<()> {
    let mut reg = Locked::open()?;
    let Some(s) = reg.node_mut(node) else { bail!("no such node: {node}") };
    match why {
        Some(w) => s["drained"] = json!({"why": w, "by": by, "at": now()}),
        None => { if let Some(o) = s.as_object_mut() { o.remove("drained"); } }
    }
    reg.mark();
    reg.commit()?;
    match why {
        Some(w) => events::emit("drained", json!({"node": node, "why": w, "actor": by})),
        None => events::emit("undrained", json!({"node": node, "actor": by})),
    }
    Ok(())
}

/// `owner`'s turn next on `node`: drained for it, so nobody else in line takes
/// the node when its holder lets go, and `owner`'s own claim does (the turn is
/// used up then). The holder keeps it meanwhile. A turn lapses when `owner`
/// stops waiting (`reap`). Returns the holder, if any.
pub fn reserve_next(node: &str, owner: &str, why: &str) -> Result<Option<String>> {
    let mut reg = Locked::open()?;
    reg.reap();
    let holder = reg.leases().get(node).and_then(|l| l["owner"].as_str()).map(str::to_string);
    if holder.as_deref() == Some(owner) {
        bail!("you hold {node} already");
    }
    let Some(s) = reg.node_mut(node) else { bail!("no such node: {node}") };
    if s["drained"].is_object() && s["drained"]["for"] != owner {
        let d = &s["drained"];
        match d["for"].as_str() {
            Some(f) => bail!("{node} is already next for {f} ({})", d["why"].as_str().unwrap_or("?")),
            None => bail!("{node} is drained ({}, by {}): ask them", d["why"].as_str().unwrap_or("?"), d["by"].as_str().unwrap_or("?")),
        }
    }
    s["drained"] = json!({"why": why, "by": owner, "at": now(), "for": owner});
    reg.mark();
    reg.commit()?;
    events::emit("next_turn", json!({"node": node, "actor": owner, "why": why, "holder": holder}));
    Ok(holder)
}

/// Where a waiting owner stands, in words.
pub fn position(owner: &str) -> Result<String> {
    let mut reg = Locked::open()?;
    reg.reap();
    Ok(position_in(&reg, owner))
}

fn position_in(reg: &Locked, owner: &str) -> String {
    let Some(me) = reg.waiters().get(owner).cloned() else { return format!("{owner} is not waiting") };
    let wanted: Vec<&Value> = reg.nodes().iter()
        .filter(|s| wants(&me, s) && s["enabled"] == true && (!s["drained"].is_object() || s["drained"]["for"] == owner)).collect();
    // A next turn is first in line, whoever asked before.
    let ahead = wanted.iter()
        .map(|s| if s["drained"]["for"] == owner { 0 } else { ahead_of(reg, owner, s).len() }).min().unwrap_or(0);
    let what = me["node"].as_str().map(str::to_string)
        .unwrap_or_else(|| format!("a {} node", me["machine"].as_str().unwrap_or("any")));
    let place = if ahead == 0 { "next in line".to_string() } else { format!("{} in line", ordinal(ahead + 1)) };
    let held: Vec<String> = wanted.iter().filter_map(|s| {
        let id = s["id"].as_str()?;
        let l = reg.leases().get(id)?;
        // What the holder said it is doing, and until when, if it said.
        let intent = l["intent"].as_str().map(|i| {
            let left = l["intent_until"].as_i64().map(|u| format!(", about {}m more", ((u - now()).max(0) + 59) / 60)).unwrap_or_default();
            format!(" (\"{i}\"{left})")
        }).unwrap_or_default();
        let yielding = if l["yield"] == true { ", yielding after its build" } else { "" };
        Some(format!("{id} held by {} for {}m{intent}{yielding}", l["owner"].as_str().unwrap_or("?"),
            (now() - l["claimed_at"].as_i64().unwrap_or(now())) / 60))
    }).collect();
    let ids: Vec<&str> = wanted.iter().filter_map(|s| s["id"].as_str()).collect();
    let mut holds: Vec<i64> = events::read(&events::Filter {
        since: chrono::Duration::days(7), kinds: vec!["release".into()], node: None, actor: None,
    }).iter()
        .filter(|e| e["node"].as_str().is_some_and(|s| ids.contains(&s)) && e["holder"] != "warmer")
        .filter_map(|e| e["held_s"].as_i64()).collect();
    holds.reverse();
    holds.truncate(20);
    holds.sort();
    let typical = holds.get(holds.len() / 2).map(|m| format!("; holds there lately last ~{}m", m / 60)).unwrap_or_default();
    format!("{place} for {what}, waiting {}m{}{typical}",
        (now() - me["since"].as_i64().unwrap_or(now())) / 60,
        if held.is_empty() { String::new() } else { format!("; {}", held.join(", ")) })
}

fn ordinal(n: usize) -> String {
    let s = match (n % 10, n % 100) { (1, 11) | (2, 12) | (3, 13) => "th", (1, _) => "st", (2, _) => "nd", (3, _) => "rd", _ => "th" };
    format!("{n}{s}")
}

/// A node joins the definitions offline, and comes online with its first
/// heartbeat. It keeps itself on the hub's build of midas (`midas node self-update`).
///
pub fn add_node(n: &Value) -> Result<()> {
    let id = n["id"].as_str().unwrap_or("");
    let ok = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
    if !ok(id) || !ok(n["machine"].as_str().unwrap_or("")) {
        bail!("node and host names are lowercase letters, digits and dashes");
    }
    if n["address"].as_str().unwrap_or("").parse::<std::net::Ipv4Addr>().is_err() {
        bail!("the address is the machine's WireGuard IPv4 address");
    }
    edit_nodes(|all| {
        if all.iter().any(|s| s["id"] == id) {
            bail!("{id} is already a node");
        }
        if all.iter().any(|s| s["address"] == n["address"] && s["ssh_port"] == n["ssh_port"]) {
            bail!("that address and port are already another node's");
        }
        let mut def = n.clone();
        def["uuid"] = json!(new_uuid()?);
        // The port the node's ssh is forwarded on: the next free one on that
        // machine from 2223, unless given.
        if def["ssh_port"].as_u64().is_none() {
            let taken: Vec<u64> = all.iter().filter(|s| s["address"] == n["address"]).filter_map(|s| s["ssh_port"].as_u64()).collect();
            def["ssh_port"] = json!((2223..).find(|p| !taken.contains(p)).unwrap());
        }
        all.push(def);
        Ok(())
    })?;
    let mut reg = Locked::open()?;
    reg.mark();
    reg.commit()?;
    events::emit("node_added", json!({"node": id, "machine": n["machine"], "address": n["address"], "port": n["ssh_port"]}));
    Ok(())
}

/// A node's identity, as opposed to its name. The name is a label people and
/// agents use, and may change (`rename_node`); the uuid does not, and the
/// machine keys what it must keep — the node's volume, its VM — on it, so a
/// rename moves no data. A random (version 4) UUID.
pub fn new_uuid() -> Result<String> {
    let mut b = [0u8; 16];
    File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut b)).context("reading /dev/urandom")?;
    b[6] = (b[6] & 0x0f) | 0x40;
    b[8] = (b[8] & 0x3f) | 0x80;
    let h: String = b.iter().map(|x| format!("{x:02x}")).collect();
    Ok(format!("{}-{}-{}-{}-{}", &h[..8], &h[8..12], &h[12..16], &h[16..20], &h[20..]))
}

pub fn is_uuid(s: &str) -> bool {
    s.len() == 36 && s.bytes().enumerate().all(|(i, b)| if [8, 13, 18, 23].contains(&i) { b == b'-' } else { b.is_ascii_hexdigit() })
}

/// The node's uuid (every node is given one when it is added).
pub fn uuid_of(node: &str) -> Option<String> {
    nodes().into_iter().find(|n| n["id"] == node)?["uuid"].as_str().filter(|u| is_uuid(u)).map(str::to_string)
}

/// Give a node another name. Everything the hub keeps about it goes with it —
/// its uuid, keys, port, its drain and its latest reading — and the old name
/// is remembered in `former_names`, so the machine's `midas setup <new>` can
/// find the node it already runs under the old one. Not while it is held:
/// the holder's ssh config names it.
pub fn rename_node(id: &str, to: &str) -> Result<()> {
    let ok = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
    if !ok(to) {
        bail!("node names are lowercase letters, digits and dashes");
    }
    if id == to {
        bail!("{id} is already called that");
    }
    // The registry's lock first: its live flags are matched to the definitions
    // by name, so both change under it.
    let mut reg = Locked::open()?;
    if reg.leases().contains_key(id) {
        bail!("{id} is held; drain it and wait for the holder first");
    }
    edit_nodes(|all| {
        if all.iter().any(|n| n["id"] == to) {
            bail!("{to} is already a node");
        }
        let Some(n) = all.iter_mut().find(|n| n["id"] == id) else { bail!("no node {id}") };
        let mut former: Vec<Value> = n["former_names"].as_array().cloned().unwrap_or_default();
        former.retain(|f| f != to && f != id);
        former.push(json!(id));
        n["former_names"] = json!(former);
        n["id"] = json!(to);
        Ok(())
    })?;
    if let Some(s) = reg.node_mut(id) {
        s["id"] = json!(to);
    }
    for w in reg.waiters_mut().values_mut().filter(|w| w["node"] == id) {
        w["node"] = json!(to);
    }
    reg.mark();
    reg.commit()?;
    drop(reg);
    match fs::rename(readings_dir().join(format!("{id}.json")), readings_dir().join(format!("{to}.json"))) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e).context("moving the node's reading"),
        _ => {}
    }
    crate::botsecrets::renamed(id, Some(to))?;
    events::emit("node_renamed", json!({"node": to, "from": id}));
    Ok(())
}

/// The hub as `host` (ADDRESS:PORT) — given only when it is one.
pub fn hub_url_at(host: &str) -> Option<String> {
    host.parse::<std::net::SocketAddrV4>().ok().map(|a| format!("http://{a}"))
}

/// Remember where a node reaches the hub, from the Host its own messages
/// (heartbeat, registration) arrive with. A Linux node dials the hub's
/// address; a Mac node's VM dials its gateway, which forwards. What the hub
/// hands a node to fetch from — the LFS endpoint and objects — must be the
/// node's address for it, or it cannot fetch at all: the Mac nodes' first
/// clones failed at the first LFS object, over and over (2026-10-16).
pub fn note_hub_url(node: &str, host: &str) -> Result<()> {
    let Some(url) = hub_url_at(host) else { return Ok(()) };
    // Read first without the lock: every heartbeat asks, and almost never changes it.
    if nodes().iter().find(|n| n["id"] == node).is_none_or(|n| n["hub_url"] == url.as_str()) {
        return Ok(());
    }
    let changed = edit_nodes(|all| {
        let Some(n) = all.iter_mut().find(|n| n["id"] == node) else { return Ok(false) };
        let changed = n["hub_url"] != url.as_str();
        n["hub_url"] = json!(url);
        Ok(changed)
    })?;
    if !changed {
        return Ok(());
    }
    events::emit("node_hub_url", json!({"node": node, "hub_url": url}));
    Ok(())
}

/// Where `node` reaches the hub, if it has said.
pub fn hub_url_of(node: &str) -> Option<String> {
    nodes().into_iter().find(|n| n["id"] == node)?["hub_url"].as_str().map(str::to_string)
}

/// One ssh-ed25519 public key, without its comment: `ssh-ed25519 AAAA…`.
pub fn ed25519_key(k: &str) -> Option<String> {
    let mut w = k.split_whitespace();
    let (kind, body) = (w.next()?, w.next()?);
    (kind == "ssh-ed25519" && body.len() >= 60 && body.len() <= 100
        && body.bytes().all(|b| b.is_ascii_alphanumeric() || b"+/=".contains(&b)))
        .then(|| format!("{kind} {body}"))
}

/// A node tells the hub its keys: the one it fetches git with and its sshd's
/// host key. Trusted by where it comes from — the node's own WireGuard
/// address, which only that machine can send from — so a node registers itself
/// with nobody copying keys around. Returns whether anything changed.
pub fn register_node(node: &str, peer: &str, git_key: &str, host_key: &str) -> Result<bool> {
    let (Some(git), Some(host)) = (ed25519_key(git_key), ed25519_key(host_key)) else {
        bail!("expected two ssh-ed25519 public keys");
    };
    let changed = edit_nodes(|all| {
        let Some(n) = all.iter_mut().find(|n| n["id"] == node) else { bail!("no node {node}") };
        if n["address"].as_str() != Some(peer) {
            bail!("{node} registers from its own address ({}), not {peer}", n["address"].as_str().unwrap_or("?"));
        }
        if n["git_key"] == git.as_str() && n["host_key"] == host.as_str() {
            return Ok(false);
        }
        n["git_key"] = json!(git);
        n["host_key"] = json!(host);
        Ok(true)
    })?;
    if !changed {
        return Ok(false);
    }
    let mut reg = Locked::open()?;
    reg.mark();
    reg.commit()?;
    events::emit("node_registered", json!({"node": node, "from": peer}));
    Ok(true)
}

pub fn remove_node(id: &str) -> Result<()> {
    let mut reg = Locked::open()?;
    if reg.leases().contains_key(id) {
        bail!("{id} is held; drain it and wait for the holder first");
    }
    edit_nodes(|all| {
        let before = all.len();
        all.retain(|n| n["id"] != id);
        if all.len() == before {
            bail!("no node {id}");
        }
        Ok(())
    })?;
    reg.mark();
    reg.commit()?;
    crate::botsecrets::renamed(id, None)?;
    events::emit("node_removed", json!({"node": id}));
    Ok(())
}

fn readings_dir() -> PathBuf {
    root().join("readings")
}

/// A heartbeat later than this after the one before is a gap: the hub was down,
/// or the node or the network was. Nodes report every minute.
pub const READING_GAP_S: i64 = 180;

/// A node's heartbeat stays silent this long before its leases may lapse
/// without one: the node is gone, not merely out of touch for a while.
const SILENT_NODE_S: i64 = 86400;

pub fn write_reading(node: &str, v: &Value) -> Result<()> {
    let dir = readings_dir();
    fs::create_dir_all(&dir)?;
    // Since when the hub has heard the node without a gap: what it knows of
    // the node's sessions only goes back that far (`idle`).
    let mut v = v.clone();
    if v["heard_since"].as_i64().is_none() {
        let at = v["at"].as_i64().unwrap_or_else(now);
        let since = reading(node)
            .filter(|p| p["at"].as_i64().is_some_and(|a| at - a <= READING_GAP_S))
            .and_then(|p| p["heard_since"].as_i64().or(p["at"].as_i64()))
            .unwrap_or(at);
        v["heard_since"] = json!(since);
    }
    store::write_atomic(&dir.join(format!("{node}.json")), v.to_string().as_bytes(), store::PUBLIC)
}

pub fn reading(node: &str) -> Option<Value> {
    fs::read_to_string(readings_dir().join(format!("{node}.json"))).ok().and_then(|t| serde_json::from_str(&t).ok())
}

/// One line for people: "GPU pool 7 % · memory 1.0 of 9.0 GiB (+7.0 cache) ·
/// 64 GB free · target/ 19 GB · load 0.4 · warm at ec992a8d · seen 20s ago".
pub fn describe_reading(r: &Value) -> String {
    let gib = |b: u64| format!("{:.1}", b as f64 / (1u64 << 30) as f64);
    let mut parts = Vec::new();
    if let Some(g) = r["gtt_pct"].as_f64() {
        parts.push(format!("GPU pool {g:.0} %"));
    }
    let used = r["mem_anon"].as_u64().or(r["mem_used"].as_u64());
    let cache = match (r["mem_used"].as_u64(), r["mem_anon"].as_u64()) {
        (Some(c), Some(a)) if c > a => format!(" (+{} cache)", gib(c - a)),
        _ => String::new(),
    };
    match (used, r["mem_max"].as_u64()) {
        (Some(u), Some(m)) => parts.push(format!("memory {} of {} GiB{cache}", gib(u), gib(m))),
        (Some(u), None) => parts.push(format!("memory {} GiB{cache}", gib(u))),
        _ => {}
    }
    if let Some(n) = r["oom_kills"].as_u64().filter(|n| *n > 0) {
        parts.push(format!("{n} OOM kill(s) since start"));
    }
    if let Some(d) = r["disk_free"].as_u64() {
        parts.push(format!("{} GB free", d / 1_000_000_000));
    }
    if let Some(t) = r["target_bytes"].as_u64() {
        parts.push(format!("target/ {} GB", t / 1_000_000_000));
    }
    if let Some(l) = r["load"].as_f64() {
        parts.push(format!("load {l:.1}"));
    }
    if let Some(w) = r["warm"].as_str().and_then(|w| w.get(..8)) {
        parts.push(format!("warm at {w}"));
    }
    if r["bot"]["running"] == true {
        let up = r["bot"]["since"].as_i64().map(|s| format!(" {}m", (now() - s).max(0) / 60)).unwrap_or_default();
        parts.push(format!("bot up{up}: {}", r["bot"]["command"].as_str().unwrap_or("?")));
    }
    if let Some(v) = r["version"].as_str() {
        parts.push(format!("midas {v}"));
    }
    let age = now() - r["at"].as_i64().unwrap_or(0);
    parts.push(if age > 180 { format!("last heard {age}s ago — node may be down") } else { format!("seen {age}s ago") });
    parts.join(" · ")
}

/// The whole picture for `status`, the MCP tools and the node client: the
/// nodes with their readings, the leases, and the queue.
pub fn snapshot() -> Result<Value> {
    let mut reg = Locked::open()?;
    reg.reap();
    reg.commit()?;
    let mut st = reg.state.clone();
    for s in st["nodes"].as_array_mut().into_iter().flatten() {
        let id = s["id"].as_str().unwrap_or("").to_string();
        s["reading"] = reading(&id).unwrap_or(Value::Null);
    }
    Ok(st)
}