garage44.eu/jeroen/midas

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

.. /src/board.rs

raw

//! The board: every session's work as a card in the stage it is in now, and
//! every node as a slot that holds one — a kanban board nobody moves by hand.
//! The hub knows where each session is, so the cards move themselves:
//!
//! | stage             | from                                                |
//! |-------------------|-----------------------------------------------------|
//! | `working`         | an open session (its hooks), seen in the last 12 h  |
//! | `waiting_for_node`| in line for a node (`waiters`), in line order       |
//! | `on_node`         | holding a node (a lease)                            |
//! | `waiting_to_land` | in the landing queue, in its order                  |
//! | `landing`         | its turn to land (gate, rebase, push)               |
//! | `landed`          | landed in the last day                              |
//!
//! A landing gate (`gate-<worktree>`) is its session's: its lease and turn show
//! on that session's card. The stages are the work's; a node is used across
//! them — a landing's gate runs on one, a session waiting to land may still
//! hold its build node — so a card keeps `node` (and `node_gate`) and
//! `node_wait` (its place in line for one) whatever lane it is in, and the
//! node's slot points at it. The workspace's own services (warmer, deployer)
//! hold nodes but are not sessions: they show in their node's slot only.
//!
//! What is sent is the state of each thing — entities keyed `card:<session>`
//! and `node:<id>` — never "what happened": a page replaces what it has, and so
//! never needs the hub's rules to work out what a change means (ws.rs).

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

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

use crate::registry::now;

/// A session not seen for this long has left the board (unless it holds,
/// waits or lands).
const WORKING_S: i64 = 12 * 3600;
/// A landed session stays in the last column this long.
const LANDED_S: i64 = 86400;
/// A command on a session's node quiet this long is shown as quiet, not as building.
const QUIET_S: u64 = 300;

pub type Entities = BTreeMap<String, Value>;

fn session_of(owner: &str) -> &str {
    owner.strip_prefix("gate-").unwrap_or(owner)
}

/// The workspace's own holders, not sessions: no card of their own.
pub fn is_service(owner: &str) -> bool {
    matches!(owner, "warmer" | "deployer" | "hub" | "web") || owner.contains(':')
}

/// The board from what the hub holds: the registry snapshot, the sessions of
/// the last day (`builds::sessions`), the names (`collab::names`) and the
/// decisions. Pure, for the tests.
/// Notes one session left another (`from`, `to`, when), for the links.
pub type Said = (String, String, i64);

pub fn compose(state: &Value, sessions: &[Value], names: &Value, decisions: &Value, archived: &Value, said: &[Said], t: i64) -> Entities {
    let mut out = Entities::new();
    let mut cards: BTreeMap<String, Value> = BTreeMap::new();
    let card = |cards: &mut BTreeMap<String, Value>, s: &str| -> Option<()> {
        if is_service(s) || cards.contains_key(s) {
            return None;
        }
        let n = &names[s];
        cards.insert(s.to_string(), json!({
            "kind": "card", "session": s, "label": n["label"], "branch": n["branch"], "link": n["link"], "repo": null,
            "stage": "working", "since": null, "active": null, "node": null, "position": null,
        }));
        Some(())
    };

    // Landed and working, from the sessions of the last day; what follows overrides.
    for se in sessions {
        let Some(s) = se["actor"].as_str().map(session_of) else { continue };
        // A session at work again after it landed is working, not landed: s450 and s453 each landed
        // and carried on, and Home showed one running while three were.
        let landed = se["running"] != true && se["outcome"] == "landed" && se["landed_at"].as_i64().is_some_and(|at| t - at < LANDED_S);
        let working = se["open"] == true && se["end"].as_i64().is_some_and(|e| t - e < WORKING_S);
        if !(landed || working) || card(&mut cards, s).is_none() {
            continue;
        }
        let c = cards.get_mut(s).expect("just made");
        for k in ["label", "branch", "link", "repo"] {
            if c[k].is_null() {
                c[k] = se[k].clone();
            }
        }
        if landed {
            c["stage"] = json!("landed");
            c["since"] = se["landed_at"].clone();
            c["sha"] = se["sha"].clone();
        } else {
            c["since"] = se["start"].clone();
            // When it last did something: its session's own clock where midas runs it, else the
            // last its hooks, builds and takes showed of it.
            c["active"] = if se["active"].is_i64() { se["active"].clone() } else { se["end"].clone() };
        }
    }

    // In line for a node, in the order the hub serves them.
    let mut waiters: Vec<(&String, &Value)> = state["waiters"].as_object().into_iter().flatten().collect();
    waiters.sort_by_key(|(_, w)| w["since"].as_i64().unwrap_or(0));
    for (i, (o, w)) in waiters.iter().enumerate() {
        let s = session_of(o);
        card(&mut cards, s);
        if let Some(c) = cards.get_mut(s) {
            let next = state["nodes"].as_array().into_iter().flatten()
                .find(|n| n["drained"]["for"] == o.as_str()).and_then(|n| n["id"].as_str());
            c["stage"] = json!("waiting_for_node");
            c["since"] = w["since"].clone();
            c["position"] = json!(i + 1);
            c["wants"] = json!(w["node"].as_str().or(w["machine"].as_str()).unwrap_or("any"));
            // Who holds the nodes it may take, and for what: "the gate waits for
            // a node" said neither, and the person could not tell why a landing
            // did not move (2026-10-31).
            let held: Vec<Value> = state["nodes"].as_array().into_iter().flatten()
                .filter(|n| crate::registry::wants(w, n))
                .filter_map(|n| {
                    let id = n["id"].as_str()?;
                    if n["enabled"] != true {
                        return Some(json!({"node": id, "offline": true}));
                    }
                    let l = &state["leases"][id];
                    let by = l["owner"].as_str()?;
                    Some(json!({"node": id, "by": session_of(by), "since": l["claimed_at"], "purpose": l["purpose"],
                                "intent": l["intent"], "intent_until": l["intent_until"], "yielding": l["yield"] == true}))
                })
                .collect();
            // Kept when a later stage wins: a landing whose gate waits for a node.
            c["node_wait"] = json!({"position": i + 1, "wants": c["wants"], "gate": o.starts_with("gate-"), "since": w["since"], "held": held});
            c["purpose"] = w["purpose"].clone();
            c["next_turn"] = json!(next);
        }
    }

    // Nodes, and who holds them.
    for n in state["nodes"].as_array().into_iter().flatten() {
        let Some(id) = n["id"].as_str() else { continue };
        let lease = &state["leases"][id];
        let holder = lease["owner"].as_str();
        let r = &n["reading"];
        out.insert(format!("node:{id}"), json!({
            "kind": "node", "id": id, "machine": n["machine"], "renderer": n["renderer"],
            "online": n["enabled"] == true, "drained": n["drained"], "holder": holder,
            "service": holder.is_some_and(is_service), "since": lease["claimed_at"],
            "version": r["version"], "load": r["load"],
        }));
        let Some(o) = holder else { continue };
        let s = session_of(o);
        card(&mut cards, s);
        if let Some(c) = cards.get_mut(s) {
            c["stage"] = json!("on_node");
            c["node"] = json!(id);
            c["since"] = lease["claimed_at"].clone();
            c["purpose"] = lease["purpose"].clone();
            c["intent"] = lease["intent"].clone();
            c["last_command"] = lease["last_command"].clone();
            c["gate"] = json!(o.starts_with("gate-"));
            // A command running on its node now (an ssh session open there).
            c["busy"] = json!(n["reading"]["sessions"].as_u64().unwrap_or(0) > 0);
            // …and when that command has printed nothing and used no CPU for
            // five minutes or more (stall.rs): s857's showed "building now" for
            // 19 hours while it waited on a pipe nothing would close.
            c["quiet"] = r["commands"].as_array().into_iter().flatten()
                .filter(|x| x["quiet_s"].as_u64().is_some_and(|q| q >= QUIET_S))
                .max_by_key(|x| x["quiet_s"].as_u64()).cloned().unwrap_or(Value::Null);
            c["node_gate"] = json!(o.starts_with("gate-"));
        }
    }

    // Landing: the queue in order, then the one landing.
    let land = &state["landing"];
    let mut queue: Vec<(&String, &Value)> = land["queue"].as_object().into_iter().flatten().collect();
    queue.sort_by_key(|(_, w)| w["since"].as_i64().unwrap_or(0));
    for (i, (o, w)) in queue.iter().enumerate() {
        let s = session_of(o);
        card(&mut cards, s);
        if let Some(c) = cards.get_mut(s) {
            c["stage"] = json!("waiting_to_land");
            c["since"] = w["since"].clone();
            c["position"] = json!(i + 1);
        }
    }
    if let Some(o) = land["holder"]["owner"].as_str() {
        let s = session_of(o);
        card(&mut cards, s);
        if let Some(c) = cards.get_mut(s) {
            c["stage"] = json!("landing");
            c["since"] = land["holder"]["granted_at"].clone();
            c["step"] = land["holder"]["step"].clone();
        }
    }

    // Put away by a person: out of the working and landed lanes. Moving on
    // (a node, a line, a landing) shows it again.
    cards.retain(|s, c| !(archived[s.as_str()].is_object() && matches!(c["stage"].as_str(), Some("working" | "landed"))));

    // Between the cards: files both change, notes they left each other,
    // decisions that concern both. Keyed by the pair, in name order.
    let mut links: BTreeMap<(String, String), Value> = BTreeMap::new();
    let pair = |a: &str, b: &str| if a < b { (a.to_string(), b.to_string()) } else { (b.to_string(), a.to_string()) };
    let link = |links: &mut BTreeMap<(String, String), Value>, a: &str, b: &str| -> Option<(String, String)> {
        let (a, b) = (session_of(a), session_of(b));
        if a == b || !cards.contains_key(a) || !cards.contains_key(b) {
            return None;
        }
        let k = pair(a, b);
        links.entry(k.clone()).or_insert_with(|| json!({"kind": "link", "a": k.0, "b": k.1, "files": [], "notes": 0, "decisions": []}));
        Some(k)
    };
    for (s, n) in names.as_object().into_iter().flatten() {
        for o in n["overlaps"].as_array().into_iter().flatten() {
            if let (Some(k), Some(files)) = (link(&mut links, s, o["with"].as_str().unwrap_or("")), o["files"].as_array()) {
                links.get_mut(&k).expect("made")["files"] = json!(files);
            }
        }
    }
    for (from, to, at) in said {
        if let Some(k) = link(&mut links, from, to) {
            let l = links.get_mut(&k).expect("made");
            l["notes"] = json!(l["notes"].as_u64().unwrap_or(0) + 1);
            if l["last_note"].as_i64().is_none_or(|x| x < *at) {
                l["last_note"] = json!(at);
            }
        }
    }
    for d in decisions.as_array().into_iter().flatten().filter(|d| d["answer"].is_null()) {
        for w in d["with"].as_array().into_iter().flatten().filter_map(Value::as_str) {
            if let Some(k) = link(&mut links, d["by"].as_str().unwrap_or(""), w) {
                links.get_mut(&k).expect("made")["decisions"].as_array_mut().expect("made").push(d["id"].clone());
            }
        }
    }
    for ((a, b), l) in links {
        out.insert(format!("link:{a}|{b}"), l);
    }

    // What needs a word: shared files, waiting notes, open decisions.
    for (s, c) in cards.iter_mut() {
        let n = &names[s.as_str()];
        let open: Vec<&str> = decisions.as_array().into_iter().flatten()
            .filter(|d| d["answer"].is_null() && (d["by"] == s.as_str() || d["with"].as_array().is_some_and(|w| w.iter().any(|x| x == s.as_str()))))
            .filter_map(|d| d["id"].as_str()).collect();
        c["badges"] = json!({
            "overlaps": n["overlaps"].as_array().map_or(0, Vec::len),
            "notes": n["notes"].as_u64().unwrap_or(0),
            "decisions": open,
        });
        out.insert(format!("card:{s}"), c.take());
    }
    out
}

/// The cards put away: those a person archived, and a checkout whose every
/// session midas runs or mirrors is archived. An editor's threads in one
/// checkout share its owner, so archiving one marks `session-<id>`, never the
/// checkout's card: it goes when the last of them does.
fn put_away(mut archived: Value, hosted: &Value) -> Value {
    let mut owners: BTreeMap<&str, bool> = BTreeMap::new();
    for m in hosted.as_array().into_iter().flatten() {
        if let Some(o) = m["owner"].as_str().filter(|o| !o.is_empty()) {
            *owners.entry(o).or_insert(true) &= m["archived"] == true;
        }
    }
    if !archived.is_object() {
        archived = json!({});
    }
    for (o, all) in owners {
        if all && archived[o].is_null() {
            archived[o] = json!({"by": "hub"});
        }
    }
    archived
}

/// The board now, from the hub's files.
pub fn gather() -> Result<Entities> {
    let state = crate::registry::snapshot()?;
    let sessions = crate::builds::sessions(LANDED_S.max(WORKING_S));
    // Notes sessions left each other in the last day, from the log.
    let said: Vec<Said> = crate::events::read(&crate::events::Filter {
        since: chrono::Duration::days(1), kinds: vec!["note".into()], node: None, actor: None,
    }).iter().filter_map(|e| {
        let (from, to) = (e["actor"].as_str()?, e["to"].as_str()?);
        let at = chrono::DateTime::parse_from_rfc3339(e["ts"].as_str()?).ok()?.timestamp();
        (from != "hub" && !from.contains(':')).then(|| (from.to_string(), to.to_string(), at))
    }).collect();
    let hosted = crate::sessions::list();
    // A session midas runs is working while it is at work, whatever its hooks reported: a session
    // resumed after its end mark had no card, and Home showed nothing running while it worked.
    let mut sessions = sessions;
    let open: std::collections::BTreeSet<String> = sessions.iter().filter(|s| s["open"] == true)
        .filter_map(|s| s["actor"].as_str().map(|a| session_of(a).to_string())).collect();
    for m in hosted.as_array().into_iter().flatten() {
        let at_work = !matches!(m["status"].as_str(), Some("stopped" | "failed")) && m["archived"] != true && m["imported"].is_null();
        // Running a turn now, rather than waiting for the person: working even if it landed today.
        let running = at_work && matches!(m["status"].as_str(), Some("working" | "starting" | "queued"));
        let Some(o) = m["owner"].as_str().filter(|o| at_work && !o.is_empty()) else { continue };
        // Its age and its last activity are the session's own, not what the marks of the last
        // day say: a session begun last week is cut at the window's edge there.
        let active = crate::sessions::active_of(m);
        if !open.contains(o) {
            sessions.push(json!({"actor": o, "open": true, "start": m["created"], "end": now(), "active": active, "running": running,
                "label": m["title"], "branch": m["branch"], "repo": m["repo"]}));
        } else {
            for se in sessions.iter_mut().filter(|s| s["actor"].as_str().map(session_of) == Some(o)) {
                if let Some(c) = m["created"].as_i64() {
                    se["start"] = json!(se["start"].as_i64().map_or(c, |s| s.min(c)));
                }
                se["active"] = json!(active);
                // Its project as midas has it now, where its start named none: a session started
                // with no project adds them as it goes, and its landing was judged live by the
                // first repository's deploys ("goes out with the next deploy" under a midas landing).
                if se["repo"].is_null() {
                    se["repo"] = m["repo"].clone();
                }
                if running {
                    se["running"] = json!(true);
                    se["end"] = json!(now());
                }
            }
        }
    }
    let archived = put_away(crate::collab::archived(), &hosted);
    let mut b = compose(&state, &sessions, &crate::collab::names(), &crate::collab::decisions(), &archived, &said, now());
    // A landing is live once its project's deploys after landings carry it (ship.rs): the
    // last step of its card. A card that never said its project is the first repository's.
    let serving = crate::ship::serving();
    let first = crate::conf::hub().first_repo().unwrap_or_default();
    for c in b.values_mut().filter(|c| c["kind"] == "card" && c["stage"] == "landed") {
        if let Some(sha) = c["sha"].as_str() {
            let repo = c["repo"].as_str().unwrap_or(&first);
            c["live"] = json!(serving.is_live(repo, sha));
        }
    }
    // Open ends: left for the next session on a machine, the board's first lane.
    for t in crate::collab::todos().as_array().into_iter().flatten().filter(|t| t["done_at"].is_null()) {
        if let Some(id) = t["id"].as_str() {
            let mut e = t.clone();
            e["kind"] = json!("todo");
            b.insert(format!("todo:{id}"), e);
        }
    }
    // The agent sessions midas runs, for the page's list (sessions.rs).
    let deploys = crate::deploy::in_flight();
    for m in hosted.as_array().into_iter().flatten() {
        if let Some(id) = m["id"].as_str() {
            let mut e = json!({"kind": "hosted"});
            // Its projects (`repo`, `repos`, `layout`) and `agent` too: the page's project filter,
            // tags and sheet read them off this entry, and have nothing else to read them from.
            for k in ["id", "title", "status", "branch", "owner", "by", "created", "updated", "base", "repo", "repos", "layout", "agent", "archived", "queue", "imported", "local", "handed", "back", "finish", "finished", "wake", "awaits", "autopilot", "template", "research"] {
                e[k] = m[k].clone();
            }
            // When it last did something (its last turn), for the page's "idle 2d".
            e["active"] = json!(crate::sessions::active_of(m));
            // What it is doing, for its card's spinner, and how long the builds it runs take as a rule.
            let (doing, expect) = crate::sessions::doing_now(id, m["status"].as_str().unwrap_or(""));
            e["doing"] = json!(doing);
            e["expect"] = json!(expect);
            // What it started that is still going: the page shows it while the agent waits.
            e["deploys"] = json!(m["owner"].as_str().and_then(|o| deploys.get(o)).cloned().unwrap_or_default());
            // Its runner stopped asking for work: paused, not at work, whatever its status last said.
            if crate::runners::is_live(m) {
                e["runner_away"] = json!(m["runner"].as_str().and_then(crate::runners::away_since));
            }
            b.insert(format!("hosted:{id}"), e);
        }
    }
    // The sessions runners, for the page's Services and its paused sessions (runners.rs).
    for r in crate::runners::board() {
        b.insert(format!("runner:{}", r["name"].as_str().unwrap_or("")), r);
    }
    Ok(b)
}

/// The board shared by every open stream: made again when the log grows (every
/// change writes to it), and at least every half minute (stages that age out,
/// node readings), never more than once at a time.
pub fn current() -> Arc<Entities> {
    struct Cache {
        stamp: (u64, i64),
        at: Option<Instant>,
        board: Arc<Entities>,
    }
    static CACHE: Mutex<Option<Cache>> = Mutex::new(None);
    // When making it last failed. The failure is an event, which moves the log's stamp and wakes
    // every page's stream, each of which made it again, failed again, and logged it again:
    // while it fails, the last board stands and it is tried again only every ten seconds.
    static FAILED: Mutex<Option<Instant>> = Mutex::new(None);
    let mut guard = CACHE.lock().unwrap_or_else(|p| p.into_inner());
    let stamp = crate::events::stamp(&crate::registry::root());
    let fresh = guard.as_ref().is_some_and(|c| c.stamp == stamp && c.at.is_some_and(|a| a.elapsed() < Duration::from_secs(30)));
    let mut failed = FAILED.lock().unwrap_or_else(|p| p.into_inner());
    let resting = failed.is_some_and(|f| f.elapsed() < Duration::from_secs(10));
    if !fresh && !resting {
        match gather() {
            Ok(b) => {
                *guard = Some(Cache { stamp, at: Some(Instant::now()), board: Arc::new(b) });
                *failed = None;
            }
            Err(e) => {
                *failed = Some(Instant::now());
                crate::events::emit("error", json!({"actor": "hub", "what": format!("the board: {e:#}")}));
            }
        }
    }
    guard.as_ref().map(|c| c.board.clone()).unwrap_or_default()
}

/// What changed from `old` to `new`: entities to set whole, and keys gone.
pub fn diff(old: &Entities, new: &Entities) -> (Entities, Vec<String>) {
    let upsert = new.iter().filter(|(k, v)| old.get(*k) != Some(v)).map(|(k, v)| (k.clone(), v.clone())).collect();
    let remove = old.keys().filter(|k| !new.contains_key(*k)).cloned().collect();
    (upsert, remove)
}

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

    #[test]
    fn each_session_is_one_card_in_the_stage_it_is_in() {
        let t = 1_000_000;
        let state = json!({
            "nodes": [
                {"id": "mac-1", "machine": "mini", "enabled": true},
                {"id": "mac-2", "machine": "mini", "enabled": true, "drained": {"why": "update", "for": "fixer"}},
                {"id": "vps-1", "machine": "vps", "enabled": true},
            ],
            "leases": {
                "mac-1": {"owner": "video", "claimed_at": t - 600, "intent": "render"},
                "vps-1": {"owner": "warmer", "claimed_at": t - 60},
                "mac-2": {"owner": "gate-lander", "claimed_at": t - 30},
            },
            "waiters": {"late": {"since": t - 10, "machine": "mini"}, "fixer": {"since": t - 20, "node": "mac-2"}},
            "landing": {"holder": {"owner": "lander", "granted_at": t - 40, "step": "gate"}, "queue": {"next": {"since": t - 5}}},
        });
        let sessions = vec![
            json!({"actor": "idle", "open": true, "end": t - 100, "start": t - 900, "label": "an idle one", "repo": "acme/podium"}),
            json!({"actor": "gone", "open": true, "end": t - WORKING_S - 1}),
            json!({"actor": "done", "outcome": "landed", "landed_at": t - 300, "sha": "abc"}),
            json!({"actor": "video", "open": true, "end": t - 5, "label": "fly-in video"}),
            json!({"actor": "again", "open": true, "running": true, "end": t, "start": t - 900, "outcome": "landed", "landed_at": t - 300}),
            // One midas runs, its runner started again a minute ago: its own clocks, not the restart's.
            json!({"actor": "slept", "open": true, "end": t, "start": t - 9 * 86400, "active": t - 3 * 86400}),
        ];
        let names = json!({"video": {"overlaps": [{"with": "idle"}], "notes": 2}});
        let decisions = json!([{"id": "d1", "by": "idle", "with": ["video"]}, {"id": "d2", "by": "idle", "answer": "x"}]);
        let said = vec![("idle".to_string(), "video".to_string(), t - 50), ("video".to_string(), "warmer".to_string(), t - 40)];
        let b = compose(&state, &sessions, &names, &decisions, &json!({"done": {"at": t}}), &said, t);
        let stage = |s: &str| b[&format!("card:{s}")]["stage"].as_str().unwrap().to_string();
        assert_eq!(stage("idle"), "working");
        assert_eq!(b["card:idle"]["repo"], "acme/podium", "its project, as its start said");
        assert_eq!(b["card:idle"]["active"], t - 100, "last seen by its hooks");
        assert_eq!((b["card:slept"]["since"].as_i64(), b["card:slept"]["active"].as_i64()), (Some(t - 9 * 86400), Some(t - 3 * 86400)),
                   "begun nine days ago, idle for three");
        assert!(!b.contains_key("card:gone"), "not seen for half a day");
        assert_eq!(stage("again"), "working", "landed, and at work again");
        assert!(!b.contains_key("card:done"), "a landed card put away stays away");
        assert_eq!(stage("video"), "on_node");
        assert_eq!(b["card:video"]["label"], "fly-in video");
        assert_eq!(b["card:video"]["intent"], "render");
        assert_eq!((stage("fixer"), b["card:fixer"]["position"].as_u64(), b["card:fixer"]["next_turn"].as_str()),
                   ("waiting_for_node".into(), Some(1), Some("mac-2")));
        assert_eq!(b["card:late"]["position"], 2);
        assert_eq!(stage("lander"), "landing", "its gate's lease and its turn are one card");
        assert_eq!((b["card:lander"]["node"].as_str(), b["card:lander"]["node_gate"].as_bool()), (Some("mac-2"), Some(true)),
                   "landing, and the node its gate is on");
        assert_eq!(b["card:lander"]["step"], "gate");
        assert_eq!(stage("next"), "waiting_to_land");
        assert!(!b.contains_key("card:warmer"), "a service is no session");
        assert_eq!((b["node:vps-1"]["holder"].as_str(), b["node:vps-1"]["service"].as_bool()), (Some("warmer"), Some(true)));
        assert_eq!(b["card:video"]["badges"], json!({"overlaps": 1, "notes": 2, "decisions": ["d1"]}));
        assert_eq!(b["card:idle"]["badges"]["decisions"], json!(["d1"]), "asked, not answered");
        // idle and video: the files both change, the note one left the other, the decision about both.
        let l = &b["link:idle|video"];
        assert_eq!((l["notes"].as_u64(), l["decisions"].clone(), l["last_note"].as_i64()), (Some(1), json!(["d1"]), Some(t - 50)));
        assert_eq!(b.keys().filter(|k| k.starts_with("link:")).count(), 1, "nothing to the warmer, which has no card");
    }

    #[test]
    fn a_landing_whose_gate_waits_for_a_node_says_so() {
        let t = 1_000_000;
        let state = json!({
            "nodes": [{"id": "mac-1", "machine": "mini", "enabled": true}],
            "leases": {"mac-1": {"owner": "builder", "claimed_at": t - 900}},
            "waiters": {"gate-lander": {"since": t - 60, "machine": "any"}},
            "landing": {"holder": {"owner": "lander", "granted_at": t - 120, "step": "gate"}, "queue": {"builder": {"since": t - 30}}},
        });
        let b = compose(&state, &[], &json!({}), &json!([]), &json!({}), &[], t);
        assert_eq!(b["card:lander"]["stage"], "landing");
        assert_eq!(b["card:lander"]["node_wait"]["position"], 1, "its gate is first in line for a node");
        assert_eq!(b["card:lander"]["node_wait"]["gate"], true);
        assert_eq!(b["card:builder"]["stage"], "waiting_to_land");
        assert_eq!(b["card:builder"]["node"], "mac-1", "waiting to land, still on its build node");
        assert_eq!(b["card:builder"]["node_gate"], false);
    }

    #[test]
    fn a_checkout_is_put_away_when_all_its_threads_are() {
        let hosted = json!([
            {"owner": "podium", "archived": true}, {"owner": "podium", "archived": null},
            {"owner": "zed", "archived": true}, {"owner": "zed", "archived": true},
            {"owner": "", "archived": true},
        ]);
        let a = put_away(json!({"session-s1": {"at": 1}}), &hosted);
        assert!(a["podium"].is_null(), "one of its threads is still at work");
        assert!(a["zed"].is_object());
        assert!(a["session-s1"].is_object(), "what a person archived stays so");
        assert!(a[""].is_null(), "an imported record has no checkout");
    }

    #[test]
    fn a_diff_carries_whole_entities_and_what_is_gone() {
        let a: Entities = [("card:x".into(), json!({"stage": "working"})), ("card:y".into(), json!({}))].into();
        let b: Entities = [("card:x".into(), json!({"stage": "on_node"})), ("node:n".into(), json!({}))].into();
        let (up, gone) = diff(&a, &b);
        assert_eq!(up.keys().collect::<Vec<_>>(), ["card:x", "node:n"]);
        assert_eq!(gone, ["card:y"]);
    }
}