garage44.eu/jeroen/midas

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

.. /src/builds.rs

raw

//! The workspace's history, kept for good so it can learn from it — the event log
//! has the same facts but is pruned after 90 days and holds everything else:
//!
//! * `builds.jsonl`: one line per ssh session on a node — how long it took,
//!   per command, node, first build of a lease or later;
//! * `takes.jsonl`: one line per take by an agent — how long it waited (0 if
//!   not at all), and the waits that gave up;
//! * `pool.jsonl`: every ten minutes, how many nodes were in the pool, and a
//!   line whenever a node was added or removed — the capacity the waits are
//!   measured against;
//! * `landings.jsonl`: one line per turn in the landing queue — what became of
//!   it (landed, failed, abandoned), how long the gate held the turn, how long
//!   it waited in line for it;
//! * `sessions.jsonl`: an agent session beginning and ending, as its hooks say
//!   (`midas session start|end`).
//!
//! The hub appends as things happen, and fills each file from the event log
//! the first time it finds it missing.

use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;

use chrono::{DateTime, Utc};
use serde_json::{json, Value};

use crate::registry;

fn file() -> PathBuf {
    registry::root().join("builds.jsonl")
}

fn takes_file() -> PathBuf {
    registry::root().join("takes.jsonl")
}

fn pool_file() -> PathBuf {
    registry::root().join("pool.jsonl")
}

fn landings_file() -> PathBuf {
    registry::root().join("landings.jsonl")
}

fn marks_file() -> PathBuf {
    registry::root().join("sessions.jsonl")
}

/// What kind of command it was, for grouping: `cargo test -p geo --release`
/// stays that, `RUSTFLAGS=… nice -n 15 cargo check --workspace` becomes
/// `cargo check --workspace`, anything else its first word.
pub fn shape(cmd: &str) -> String {
    // The first piece of a compound command that does something.
    for part in cmd.split(|c| c == ';' || c == '|' || c == '&').map(str::trim).filter(|p| !p.is_empty()) {
        let words = shell_words(part);
        let mut w: Vec<&str> = words.iter().map(String::as_str).collect();
        // Wrappers and environment settings in front of the real command.
        loop {
            match w.first() {
                Some(t) if t.contains('=') && !t.starts_with('-') => { w.remove(0); }
                Some(&("nice" | "time" | "env" | "exec" | "command")) => {
                    w.remove(0);
                    if w.first() == Some(&"-n") { w.drain(..2.min(w.len())); }
                }
                Some(&"timeout") => { w.drain(..2.min(w.len())); }
                _ => break,
            }
        }
        let Some(first) = w.first() else { continue };
        if *first == "cd" || *first == "export" || *first == "set" || *first == "source" || *first == "." {
            continue;
        }
        if *first != "cargo" {
            return first.trim_matches(['\'', '"']).to_string();
        }
        let mut out = vec!["cargo"];
        let mut i = 1;
        // `cargo +nightly test` → keep the toolchain.
        while i < w.len() && w[i].starts_with('+') {
            out.push(w[i]);
            i += 1;
        }
        if let Some(sub) = w.get(i) {
            out.push(sub);
            i += 1;
        }
        while i < w.len() {
            match w[i] {
                "--" => break,
                "-p" | "--package" | "--target" | "--bin" | "--example" | "--test" => {
                    if let Some(v) = w.get(i + 1) {
                        out.push(w[i]);
                        out.push(v);
                    }
                    i += 2;
                }
                "--workspace" | "--release" | "--all-targets" | "--no-run" | "--lib" => {
                    out.push(w[i]);
                    i += 1;
                }
                _ => i += 1,
            }
        }
        return out.join(" ");
    }
    String::new()
}

/// Words as a shell would split them: quotes keep spaces in (and are removed).
fn shell_words(s: &str) -> Vec<String> {
    let (mut out, mut cur, mut quote, mut any) = (Vec::new(), String::new(), None::<char>, false);
    for c in s.chars() {
        match (quote, c) {
            (Some(q), c) if c == q => quote = None,
            (Some(_), c) => cur.push(c),
            (None, '\'' | '"') => { quote = Some(c); any = true; }
            (None, c) if c.is_whitespace() => {
                if any || !cur.is_empty() { out.push(std::mem::take(&mut cur)); }
                any = false;
            }
            (None, c) => cur.push(c),
        }
    }
    if any || !cur.is_empty() { out.push(cur); }
    out
}

/// What an agent's shell command runs on a node, when it is `ssh <node> '<command>'`:
/// the node and the command. Only a node of the workspace counts (`ssh host` is no build).
pub fn on_node(cmd: &str) -> Option<(String, String)> {
    ssh_of(cmd).filter(|(node, _)| registry::is_node(node))
}

/// `ssh <where> <command…>` in a shell command line: where to, and the command.
fn ssh_of(cmd: &str) -> Option<(String, String)> {
    let w = shell_words(cmd);
    let at = w.iter().position(|x| x == "ssh")?;
    let mut i = at + 1;
    // Its options, and the value of those that take one.
    while w.get(i).is_some_and(|x| x.starts_with('-')) {
        i += if matches!(w[i].as_str(), "-o" | "-p" | "-i" | "-l" | "-J" | "-F") { 2 } else { 1 };
    }
    let node = w.get(i)?;
    // Up to where the local shell takes over again: a pipe, a redirect, the next command.
    let rest: Vec<&str> = w[i + 1..].iter().map(String::as_str)
        .take_while(|x| !matches!(*x, "|" | "||" | "&&" | ";" | "&") && !x.starts_with('>') && !x.starts_with("2>"))
        .collect();
    (!rest.is_empty()).then(|| (node.clone(), rest.join(" ")))
}

/// How long a shell command an agent runs takes as a rule, in seconds, when it
/// is a build on a node (`on_node`): the median of that kind of command's
/// successful runs on the node over 30 days, else on its machine, else on any
/// node. None for anything else, and for a kind never run.
pub fn typical(cmd: &str) -> Option<i64> {
    let (node, remote) = on_node(cmd)?;
    let m = medians(&shape(&remote), 30 * 86400);
    m.by_node.get(&node).copied()
        .or_else(|| machine_of(&node).as_str().and_then(|k| m.by_machine.get(k)).copied())
        .or(m.all)
}

fn machine_of(node: &str) -> Value {
    registry::nodes().into_iter().find(|n| n["id"] == node).map(|n| n["machine"].clone()).unwrap_or(Value::Null)
}

fn line(ev: &Value, first: bool) -> Value {
    let cmd = ev["command"].as_str().unwrap_or("");
    json!({
        "ts": ev["ts"], "node": ev["node"], "machine": machine_of(ev["node"].as_str().unwrap_or("")),
        "actor": ev["actor"], "shape": shape(cmd), "command": cmd.chars().take(200).collect::<String>(),
        "seconds": ev["duration_s"], "exit": ev["exit"], "oom_kills": ev["oom_kills"],
        // The first build of a lease pays for whatever the node lacks.
        "first_build_in_lease": first,
    })
}

fn append_to(path: PathBuf, v: &Value) {
    // One write, the line with its newline: `writeln!` wrote them apart, so two threads' lines
    // could interleave, and a reader could find a line with no end yet.
    if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(path) {
        let _ = f.write_all(format!("{v}\n").as_bytes());
    }
}

fn append(v: &Value) {
    append_to(file(), v);
}

/// A take, a wait given up, a node added or removed, or a turn at landing, as a
/// history line.
fn history_line(ev: &Value) -> Option<(PathBuf, Value)> {
    let actor = ev["actor"].as_str().unwrap_or("");
    match ev["kind"].as_str()? {
        // The warmer takes nodes too, but it never waits for anyone.
        "claim" if actor != "warmer" => Some((takes_file(), json!({
            "ts": ev["ts"], "actor": actor, "node": ev["node"], "waited_s": ev["waited_s"].as_i64().unwrap_or(0),
        }))),
        "gave_up" if actor != "warmer" => Some((takes_file(), json!({
            "ts": ev["ts"], "actor": actor, "gave_up": true, "waited_s": ev["waited_s"].as_i64().unwrap_or(0),
        }))),
        "node_added" | "node_removed" => Some((pool_file(), json!({
            "ts": ev["ts"], "event": ev["kind"], "node": ev["node"], "machine": ev["machine"],
        }))),
        "landing_done" => Some((landings_file(), json!({
            "ts": ev["ts"], "actor": actor, "branch": ev["branch"], "outcome": ev["outcome"], "sha": ev["sha"],
            "held_s": ev["held_s"], "waited_s": ev["waited_s"],
        }))),
        "session_start" | "session_end" => Some((marks_file(), json!({
            "ts": ev["ts"], "actor": actor, "event": if ev["kind"] == "session_end" { "end" } else { "start" },
            "branch": ev["branch"], "reason": ev["reason"], "repo": ev["repo"],
        }))),
        // What to call the session: the start of its first prompt (the prompt hook).
        "session_label" => Some((marks_file(), json!({
            "ts": ev["ts"], "actor": actor, "event": "label", "label": ev["label"], "branch": ev["branch"],
        }))),
        _ => None,
    }
}

/// Every event the hub writes passes here: the ones the history keeps are
/// copied into it.
pub fn observe(ev: &Value) {
    if matches!(ev["kind"].as_str(), Some("deploy_published" | "deploy_failed")) {
        crate::deploy::finished(ev);
    }
    if ev["kind"] == "landing_done" && ev["outcome"] == "landed" {
        crate::collab::landed(ev["actor"].as_str().unwrap_or(""), ev["branch"].as_str(), ev["sha"].as_str());
    }
    if ev["kind"] == "ssh_session" {
        session_closed(ev);
        if ev["phase"] == "close" {
            if let Some(node) = ev["node"].as_str() {
                let _ = registry::session_closed_on(node);
            }
        }
        return;
    }
    if let Some((path, line)) = history_line(ev) {
        // A file filled from the log now already has this event in it.
        let had = path.exists();
        ensure_history();
        if had {
            append_to(path, &line);
        }
    }
    // After its mark is kept: what the session leaves behind goes with it.
    if ev["kind"] == "session_end" {
        crate::collab::session_ended(ev["actor"].as_str().unwrap_or(""), ev["reason"].as_str());
    }
}

/// How many nodes are in the pool now (the hub samples it every ten minutes).
pub fn sample_pool() {
    let st = match registry::snapshot() { Ok(s) => s, Err(_) => return };
    let nodes = st["nodes"].as_array().cloned().unwrap_or_default();
    let in_pool = nodes.iter().filter(|n| n["enabled"] == true && !n["drained"].is_object()).count();
    ensure_history();
    append_to(pool_file(), &json!({
        "ts": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), "in_pool": in_pool, "nodes": nodes.len(),
    }));
}

/// The first time: takes, node changes and landings still in the event log.
/// Each file is filled on its own, so one added later is backfilled too.
fn ensure_history() {
    if takes_file().exists() && pool_file().exists() && landings_file().exists() && marks_file().exists() {
        return;
    }
    let f = crate::events::Filter {
        since: chrono::Duration::days(crate::events::KEEP_DAYS),
        kinds: vec!["claim".into(), "gave_up".into(), "node_added".into(), "node_removed".into(),
                    "node_online".into(), "node_offline".into(), "landing_done".into(),
                    "session_start".into(), "session_end".into(), "session_label".into()],
        node: None, actor: None,
    };
    let (mut takes, mut pool, mut landings, mut marks) = (String::new(), String::new(), String::new(), String::new());
    // The pool's size before sampling began, from nodes going on and offline —
    // counting only nodes that exist now or were added in the window (the log
    // still names nodes of an older setup that were never formally removed).
    let events = crate::events::read_at(&registry::root(), &f);
    let mut known: std::collections::HashSet<String> =
        registry::nodes().iter().filter_map(|n| n["id"].as_str().map(str::to_string)).collect();
    known.extend(events.iter().filter(|e| e["kind"] == "node_added").filter_map(|e| e["node"].as_str().map(str::to_string)));
    let mut online: HashMap<String, bool> = HashMap::new();
    for ev in events {
        let node = ev["node"].as_str().unwrap_or("").to_string();
        if ev["kind"] == "node_removed" {
            online.remove(&node);
        }
        if let Some(on) = match ev["kind"].as_str() { Some("node_online") => Some(true), Some("node_offline") => Some(false), _ => None } {
            if known.contains(&node) {
                online.insert(node, on);
                pool += &format!("{}\n", json!({"ts": ev["ts"], "in_pool": online.values().filter(|v| **v).count()}));
            }
            continue;
        }
        if let Some((path, line)) = history_line(&ev) {
            let into = if path == takes_file() { &mut takes } else if path == landings_file() { &mut landings }
                else if path == marks_file() { &mut marks } else { &mut pool };
            *into += &format!("{line}\n");
        }
    }
    if !takes_file().exists() { let _ = fs::write(takes_file(), takes); }
    if !pool_file().exists() { let _ = fs::write(pool_file(), pool); }
    if !landings_file().exists() { let _ = fs::write(landings_file(), landings); }
    if !marks_file().exists() { let _ = fs::write(marks_file(), marks); }
}

fn read_since(path: PathBuf, since_s: i64) -> Vec<Value> {
    // A `since` from a query, held to what chrono can subtract (beyond, it panics): a century.
    let from = (Utc::now() - chrono::Duration::seconds(since_s.clamp(0, 100 * 365 * 86_400))).timestamp_millis();
    timed_lines(&path).iter().filter(|(t, _)| *t >= from).filter_map(|(_, l)| serde_json::from_str(l).ok()).collect()
}

/// A history file's lines with their times, kept between reads and read on only as far as the
/// file grew. Read whole and parsed each time, `builds.jsonl` (3.7 MB, kept for good) was parsed
/// at every change on the board, to keep a day of it, and twice for every claim. The files are
/// only appended to; one that is not what was kept (shorter, or another file at its start: the
/// backfill writes one whole) is read again from the start.
fn timed_lines(path: &std::path::Path) -> std::sync::Arc<Vec<(i64, String)>> {
    use std::io::{Read, Seek, SeekFrom};
    use std::os::unix::fs::MetadataExt;
    use std::sync::{Arc, Mutex};
    struct Kept {
        ino: u64,
        len: u64,
        head: Vec<u8>,
        lines: Arc<Vec<(i64, String)>>,
    }
    static KEPT: Mutex<Vec<(PathBuf, Kept)>> = Mutex::new(Vec::new());
    let Ok(mut f) = fs::File::open(path) else { return Arc::default() };
    let Ok(meta) = f.metadata() else { return Arc::default() };
    let mut head = vec![0u8; 64.min(meta.len() as usize)];
    if f.read_exact(&mut head).is_err() {
        return Arc::default();
    }
    let mut kept = KEPT.lock().unwrap_or_else(|p| p.into_inner());
    let at = kept.iter().position(|(p, _)| p == path);
    let same = |k: &Kept| k.ino == meta.ino() && k.len <= meta.len() && head.starts_with(&k.head[..k.head.len().min(head.len())]);
    let (start, mut lines) = match at.map(|i| &kept[i].1) {
        Some(k) if same(k) => (k.len, k.lines.clone()),
        _ => (0, Arc::new(Vec::new())),
    };
    if start < meta.len() {
        let mut more = Vec::new();
        if f.seek(SeekFrom::Start(start)).is_err() || f.read_to_end(&mut more).is_err() {
            return lines;
        }
        // Up to the last whole line: one being written is read once it ends.
        let end = more.iter().rposition(|&b| b == b'\n').map_or(0, |i| i + 1);
        let add = Arc::make_mut(&mut lines);
        for l in String::from_utf8_lossy(&more[..end]).lines() {
            let ts = serde_json::from_str::<Value>(l).ok()
                .and_then(|v| v["ts"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()));
            if let Some(t) = ts {
                add.push((t.timestamp_millis(), l.to_string()));
            }
        }
        let k = Kept { ino: meta.ino(), len: start + end as u64, head, lines: lines.clone() };
        match at {
            Some(i) => kept[i].1 = k,
            None => kept.push((path.to_path_buf(), k)),
        }
    }
    lines
}

/// The takes and the pool's history since `since_s` seconds ago.
pub fn history(since_s: i64) -> Value {
    ensure_history();
    json!({"takes": read_since(takes_file(), since_s), "pool": read_since(pool_file(), since_s)})
}

/// The session hooks' marks since `since_s` seconds ago, oldest first.
pub fn marks(since_s: i64) -> Vec<Value> {
    ensure_history();
    read_since(marks_file(), since_s)
}

/// The turns at landing since `since_s` seconds ago, oldest first.
pub fn landings(since_s: i64) -> Vec<Value> {
    ensure_history();
    read_since(landings_file(), since_s)
}

/// What each session did with the workspace since `since_s` seconds ago, newest
/// first. A session is an owner — the worktree an agent works in — and what it
/// leaves behind is in the kept files: its builds, its takes, its turns at
/// landing, and the marks its session hooks send (`midas session start|end`).
/// It is seen from the first of those to the last, and its time to land runs
/// from that first one to the landing. Sessions from before the hooks sent
/// marks (`start_from: "workspace"`) begin at their first take, which is later
/// than they really began.
///
/// A session that began before the window is cut at the window's edge; ask for
/// a wider one to see it whole.
pub fn sessions(since_s: i64) -> Vec<Value> {
    sessions_from(&read(since_s), &history(since_s)["takes"], &landings(since_s), &read_since(marks_file(), since_s))
}

fn ts_of(v: &Value) -> Option<i64> {
    v["ts"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()).map(|t| t.timestamp())
}

pub fn sessions_from(builds: &[Value], takes: &Value, landings: &[Value], marks: &[Value]) -> Vec<Value> {
    #[derive(Default)]
    struct S {
        start: i64,
        end: i64,
        builds: u64,
        failed: u64,
        build_s: i64,
        commands: u64,
        takes: u64,
        waited_s: i64,
        nodes: std::collections::BTreeSet<String>,
        branch: Option<String>,
        attempts: u64,
        landed_at: Option<i64>,
        gate_s: Option<i64>,
        land_wait_s: Option<i64>,
        sha: Option<String>,
        last_outcome: Option<String>,
        /// A session hook said when it began, rather than its first take.
        started: bool,
        ended: Option<i64>,
        label: Option<String>,
        /// Its repository (`owner/name`), as its start said: the project it is in.
        repo: Option<String>,
    }
    let mut all: HashMap<String, S> = HashMap::new();
    fn at<'a>(all: &'a mut HashMap<String, S>, actor: &str, from: i64, to: i64) -> Option<&'a mut S> {
        // The warmer is the workspace's own.
        if actor.is_empty() || actor == "warmer" {
            return None;
        }
        // A landing gate takes its node as `gate-<worktree>` (cartopolis's
        // verify-branch), so the lease is its own; the time is the session's.
        let actor = actor.strip_prefix("gate-").unwrap_or(actor);
        let s = all.entry(actor.to_string()).or_insert(S { start: from, end: to, ..S::default() });
        s.start = s.start.min(from);
        s.end = s.end.max(to);
        Some(s)
    }
    for b in builds {
        let (Some(t), secs) = (ts_of(b), b["seconds"].as_i64().unwrap_or(0)) else { continue };
        let Some(s) = at(&mut all, b["actor"].as_str().unwrap_or(""), t - secs, t) else { continue };
        s.commands += 1;
        if let Some(n) = b["node"].as_str() {
            s.nodes.insert(n.to_string());
        }
        if b["shape"].as_str().is_some_and(|x| x.starts_with("cargo")) {
            s.builds += 1;
            s.build_s += secs;
            s.failed += (b["exit"].as_i64() != Some(0)) as u64;
        }
    }
    for k in takes.as_array().into_iter().flatten() {
        let (Some(t), w) = (ts_of(k), k["waited_s"].as_i64().unwrap_or(0)) else { continue };
        let Some(s) = at(&mut all, k["actor"].as_str().unwrap_or(""), t - w, t) else { continue };
        s.waited_s += w;
        if k["gave_up"] != true {
            s.takes += 1;
        }
    }
    // Sessions whose project was said by `project_add` (a start with reason `project`).
    let mut said: std::collections::HashSet<String> = std::collections::HashSet::new();
    // The session hooks' marks: the session's true ends, where it has them.
    for k in marks {
        let Some(t) = ts_of(k) else { continue };
        // A session started again by its runner (a restart, a deploy) is the same session, not
        // a new one and not one at work: its revival is no start and no activity.
        if k["event"] == "start" && k["reason"] == "revive" {
            continue;
        }
        let Some(s) = at(&mut all, k["actor"].as_str().unwrap_or(""), t, t) else { continue };
        match k["event"].as_str() {
            Some("start") => s.started = true,
            Some("end") => s.ended = Some(t),
            Some("label") => s.label = k["label"].as_str().map(str::to_string),
            _ => {}
        }
        if s.branch.is_none() {
            s.branch = k["branch"].as_str().map(str::to_string);
        }
        // Its project: the first one it added, where it added one. A session started from the
        // page sits in a folder inside the workspace's first checkout, so its startup hook names
        // that repository whatever it works in: s517 worked in midas only, was taken for a
        // cartopolis session, and its landing was never live by cartopolis's deploys (2026-10-29).
        let actor = k["actor"].as_str().unwrap_or("");
        if k["reason"] == "project" && k["repo"].is_string() && said.insert(actor.to_string()) {
            s.repo = k["repo"].as_str().map(str::to_string);
        } else if s.repo.is_none() {
            s.repo = k["repo"].as_str().map(str::to_string);
        }
    }
    for l in landings {
        let Some(t) = ts_of(l) else { continue };
        let (held, waited) = (l["held_s"].as_i64().unwrap_or(0), l["waited_s"].as_i64().unwrap_or(0));
        let Some(s) = at(&mut all, l["actor"].as_str().unwrap_or(""), t - held - waited, t) else { continue };
        s.attempts += 1;
        s.branch = l["branch"].as_str().map(str::to_string).or(s.branch.take());
        s.last_outcome = l["outcome"].as_str().map(str::to_string);
        if l["outcome"] == "landed" {
            s.landed_at = Some(t);
            s.gate_s = Some(held);
            s.land_wait_s = Some(waited);
            s.sha = l["sha"].as_str().map(str::to_string);
        }
    }
    let mut out: Vec<(i64, Value)> = all.into_iter().map(|(actor, s)| (s.end, json!({
        "actor": actor, "branch": s.branch, "label": s.label, "repo": s.repo, "link": crate::collab::link(&actor),
        "start": s.start, "end": s.end, "span_s": s.end - s.start,
        "commands": s.commands, "builds": s.builds, "failed_builds": s.failed, "build_s": s.build_s,
        "takes": s.takes, "waited_s": s.waited_s, "nodes": s.nodes,
        "landing_attempts": s.attempts, "outcome": s.last_outcome,
        "landed_at": s.landed_at, "sha": s.sha, "gate_s": s.gate_s, "land_wait_s": s.land_wait_s,
        "time_to_land_s": s.landed_at.map(|t| t - s.start),
        "start_from": if s.started { "hook" } else { "workspace" },
        // Still going: no end mark since its last start or activity.
        "open": s.started && s.ended.is_none_or(|e| e < s.end),
    }))).collect();
    out.sort_by(|a, b| b.0.cmp(&a.0));
    out.into_iter().map(|(_, v)| v).collect()
}

/// A session closed on a node (the hub calls this from the event log).
pub fn session_closed(ev: &Value) {
    if ev["kind"] != "ssh_session" || ev["phase"] != "close" || !ev["duration_s"].is_number() {
        return;
    }
    let node = ev["node"].as_str().unwrap_or("").to_string();
    // Count the lease's builds on the lease itself. Only builds: the first
    // session is usually `midas take`'s own check of the checkout.
    let is_build = shape(ev["command"].as_str().unwrap_or("")).starts_with("cargo");
    let first = is_build && registry::Locked::open().ok().map(|mut reg| {
        let Some(l) = reg.leases_mut().get_mut(&node) else { return false };
        let n = l["builds"].as_u64().unwrap_or(0);
        l["builds"] = json!(n + 1);
        reg.mark();
        let _ = reg.commit();
        n == 0
    }).unwrap_or(false);
    ensure_backfilled();
    append(&line(ev, first));
}

/// The first time: the sessions still in the event log, oldest first, with
/// "first after a claim" worked out from the claims beside them.
pub fn ensure_backfilled() {
    if file().exists() {
        return;
    }
    let f = crate::events::Filter {
        since: chrono::Duration::days(crate::events::KEEP_DAYS), kinds: vec!["claim".into(), "ssh_session".into()],
        node: None, actor: None,
    };
    let mut fresh: HashMap<String, bool> = HashMap::new();
    let mut out = String::new();
    for ev in crate::events::read_at(&registry::root(), &f) {
        let node = ev["node"].as_str().unwrap_or("").to_string();
        if ev["kind"] == "claim" {
            fresh.insert(node, true);
        } else if ev["phase"] == "close" && ev["duration_s"].is_number() {
            let is_build = shape(ev["command"].as_str().unwrap_or("")).starts_with("cargo");
            let first = is_build && fresh.insert(node, false).unwrap_or(false);
            out += &format!("{}\n", line(&ev, first));
        }
    }
    let _ = fs::write(file(), out);
}

/// The records since `since` seconds ago.
pub fn read(since_s: i64) -> Vec<Value> {
    ensure_backfilled();
    read_since(file(), since_s)
}

/// How long one kind of command takes, in seconds: the median of its
/// successful runs per node, per machine, and over all of them. A failed run
/// says nothing about speed — a gate red on formatting ends in two seconds.
pub fn medians(shape: &str, since_s: i64) -> Medians {
    let mut by_node: HashMap<String, Vec<i64>> = HashMap::new();
    let mut by_machine: HashMap<String, Vec<i64>> = HashMap::new();
    let mut all = Vec::new();
    // As `speed_factors` counts: the first build of a lease pays for what the
    // node lacked, and the warmer's runs start cold by design.
    for r in read(since_s).iter().filter(|r| r["shape"] == shape && r["exit"] == 0
                                         && r["first_build_in_lease"] != true && r["actor"] != "warmer") {
        let Some(s) = r["seconds"].as_i64() else { continue };
        all.push(s);
        if let Some(n) = r["node"].as_str() {
            by_node.entry(n.to_string()).or_default().push(s);
        }
        if let Some(m) = r["machine"].as_str() {
            by_machine.entry(m.to_string()).or_default().push(s);
        }
    }
    let median = |mut v: Vec<i64>| {
        v.sort();
        v[v.len() / 2]
    };
    let per = |m: HashMap<String, Vec<i64>>| m.into_iter().map(|(k, v)| (k, median(v))).collect();
    Medians { by_node: per(by_node), by_machine: per(by_machine), all: (!all.is_empty()).then(|| median(all)) }
}

#[derive(Default)]
pub struct Medians {
    pub by_node: HashMap<String, i64>,
    pub by_machine: HashMap<String, i64>,
    /// Over every node: what a node that never ran it is scaled from.
    pub all: Option<i64>,
}

/// How fast each node and machine is at building in general, as a factor of
/// the workspace's typical time: 0.5 builds in half the time, 2.0 takes twice as
/// long. For every kind of cargo command run on more than one machine, each
/// machine's median against the median of all its runs; then the weighted
/// geometric mean over the kinds. Only later builds of a lease count — the
/// first pays for what the node lacked, which says nothing about its speed.
pub fn speed_factors(since_s: i64) -> (HashMap<String, f64>, HashMap<String, f64>) {
    speed_factors_from(&read(since_s))
}

pub fn speed_factors_from(builds: &[Value]) -> (HashMap<String, f64>, HashMap<String, f64>) {
    let mut by_shape: HashMap<&str, Vec<&Value>> = HashMap::new();
    for r in builds.iter().filter(|r| r["exit"] == 0 && r["first_build_in_lease"] != true && r["actor"] != "warmer") {
        let Some(shape) = r["shape"].as_str().filter(|s| s.starts_with("cargo")) else { continue };
        if r["seconds"].as_i64().is_some_and(|s| s > 0) {
            by_shape.entry(shape).or_default().push(r);
        }
    }
    let median = |mut v: Vec<f64>| -> f64 {
        v.sort_by(f64::total_cmp);
        v[v.len() / 2]
    };
    let mut sums: [HashMap<String, (f64, f64)>; 2] = [HashMap::new(), HashMap::new()];
    for runs in by_shape.values() {
        let machines: std::collections::HashSet<&str> = runs.iter().filter_map(|r| r["machine"].as_str()).collect();
        if machines.len() < 2 {
            continue; // one machine alone says nothing about which is faster
        }
        let all = median(runs.iter().map(|r| r["seconds"].as_f64().unwrap_or(0.0)).collect());
        for (i, key) in ["node", "machine"].iter().enumerate() {
            let mut groups: HashMap<&str, Vec<f64>> = HashMap::new();
            for r in runs {
                if let Some(k) = r[*key].as_str() {
                    groups.entry(k).or_default().push(r["seconds"].as_f64().unwrap_or(0.0));
                }
            }
            for (k, v) in groups {
                let w = (v.len() as f64).min(20.0);
                let e = sums[i].entry(k.to_string()).or_insert((0.0, 0.0));
                e.0 += w * (median(v) / all).ln();
                e.1 += w;
            }
        }
    }
    let [nodes, machines] = sums.map(|m| m.into_iter().map(|(k, (s, w))| (k, (s / w).exp())).collect());
    (nodes, machines)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn commands_are_grouped_by_what_they_build() {
        assert_eq!(shape("cargo test -p cartopolis_geo -- --nocapture"), "cargo test -p cartopolis_geo");
        assert_eq!(shape("RUSTFLAGS='-C x' nice -n 15 cargo check --workspace --exclude a --all-targets"),
                   "cargo check --workspace --all-targets");
        assert_eq!(shape("cd crates/x && timeout 300 cargo +nightly build --release --target wasm32-unknown-unknown"),
                   "cargo +nightly build --release --target wasm32-unknown-unknown");
        assert_eq!(shape("WGPU_BACKEND=vulkan cargo run -p cartopolis -- --shot /tmp/x.png"), "cargo run -p cartopolis");
        assert_eq!(shape("git log --oneline -1"), "git");
        assert_eq!(shape("scp -t /tmp"), "scp");
        assert_eq!(shape(""), "");
    }

    #[test]
    fn an_agents_build_is_the_command_it_sends_over_ssh() {
        let of = |c: &str| ssh_of(c).map(|(n, r)| format!("{n}: {}", shape(&r)));
        assert_eq!(of("ssh vps-1 'cargo test -p cartopolis_geo' 2>&1 | tail -30").as_deref(), Some("vps-1: cargo test -p cartopolis_geo"));
        assert_eq!(of("cd x && ssh -o BatchMode=yes mac-1 cargo check --workspace; echo done").as_deref(), Some("mac-1: cargo check --workspace"));
        assert_eq!(of("ssh vps-1 'cd web && bun test' > /tmp/out").as_deref(), Some("vps-1: bun"));
        assert_eq!(of("cargo test"), None);
        assert_eq!(of("ssh host"), None, "a login is no command");
    }

    #[test]
    fn a_session_runs_from_its_first_take_to_its_landing() {
        let builds = vec![
            json!({"ts": "2026-10-17T10:10:00Z", "actor": "s1", "node": "vps-1", "shape": "cargo test", "seconds": 300, "exit": 0}),
            json!({"ts": "2026-10-17T10:20:00Z", "actor": "s1", "node": "vps-1", "shape": "cargo check", "seconds": 60, "exit": 101}),
            json!({"ts": "2026-10-17T10:21:00Z", "actor": "s1", "node": "vps-1", "shape": "git", "seconds": 0, "exit": 0}),
            json!({"ts": "2026-10-17T10:00:00Z", "actor": "warmer", "node": "vps-1", "shape": "cargo check", "seconds": 900, "exit": 0}),
        ];
        // Asked for a node at 09:55, got it at 10:00; the gate waited ten minutes for one.
        let takes = json!([
            {"ts": "2026-10-17T10:00:00Z", "actor": "s1", "node": "vps-1", "waited_s": 300},
            {"ts": "2026-10-17T10:45:00Z", "actor": "gate-s1", "node": "vps-1", "waited_s": 600},
        ]);
        let landings = vec![
            json!({"ts": "2026-10-17T10:40:00Z", "actor": "s1", "branch": "b", "outcome": "failed", "held_s": 400, "waited_s": 0}),
            json!({"ts": "2026-10-17T11:00:00Z", "actor": "s1", "branch": "b", "outcome": "landed", "sha": "abc", "held_s": 600, "waited_s": 120}),
        ];
        let s = sessions_from(&builds, &takes, &landings, &[]);
        assert_eq!(s.len(), 1, "the warmer is no session");
        let s = &s[0];
        assert_eq!(s["actor"], "s1");
        assert_eq!(s["branch"], "b");
        assert_eq!(s["builds"], 2);
        assert_eq!(s["failed_builds"], 1);
        assert_eq!(s["build_s"], 360);
        assert_eq!(s["waited_s"], 900, "the gate's wait is the session's");
        assert_eq!(s["landing_attempts"], 2);
        assert_eq!(s["outcome"], "landed");
        assert_eq!(s["gate_s"], 600);
        // 09:55 to 11:00.
        assert_eq!(s["time_to_land_s"], 65 * 60);
        assert_eq!(s["span_s"], 65 * 60);
        assert_eq!(s["start_from"], "workspace");

        // With the hooks' marks, it began when the session did, and ended.
        let marks = vec![
            json!({"ts": "2026-10-17T09:30:00Z", "actor": "s1", "event": "start", "branch": "worktree-s1", "repo": "acme/podium"}),
            json!({"ts": "2026-10-17T11:05:00Z", "actor": "s1", "event": "end"}),
        ];
        let s = &sessions_from(&builds, &takes, &landings, &marks)[0];
        assert_eq!(s["time_to_land_s"], 90 * 60);
        assert_eq!(s["span_s"], 95 * 60);
        assert_eq!(s["branch"], "b", "the landed branch names it, not the worktree");
        assert_eq!(s["open"], false);
        assert_eq!(s["repo"], "acme/podium", "its project, from its start");
        // Started from the page: the folder's enclosing checkout first, then the project it added.
        let mut added = marks.clone();
        added.insert(1, json!({"ts": "2026-10-17T09:30:05Z", "actor": "s1", "event": "start", "reason": "project", "repo": "acme/midas"}));
        added.insert(2, json!({"ts": "2026-10-17T09:40:00Z", "actor": "s1", "event": "start", "reason": "project", "repo": "acme/podium"}));
        assert_eq!(sessions_from(&builds, &takes, &landings, &added)[0]["repo"], "acme/midas", "the first project it added");

        // Its runner started again two days on and loaded it: the same session, still idle.
        let mut later = marks.clone();
        later.push(json!({"ts": "2026-10-19T09:44:57Z", "actor": "s1", "event": "start", "reason": "revive"}));
        let s = &sessions_from(&builds, &takes, &landings, &later)[0];
        assert_eq!((s["span_s"].as_i64(), s["open"].as_bool()), (Some(95 * 60), Some(false)), "a revival is no start and no activity");
        // Seen only through a revival, inside the window: no session at all.
        let only = vec![json!({"ts": "2026-10-19T09:44:57Z", "actor": "s9", "event": "start", "reason": "revive"})];
        assert!(sessions_from(&[], &json!([]), &[], &only).is_empty());
    }
}