garage44.eu/jeroen/midas

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

.. /src/tests.rs

raw

//! The rules that decide who gets a node, against a scratch state directory.
//!
//! The state is found through `MIDAS_STATE`, a process-wide setting, so these
//! run one at a time behind a lock.

use std::sync::Mutex;

use serde_json::{json, Value};

use crate::registry::{self, Claim, Locked};

pub(crate) static SERIAL: Mutex<()> = Mutex::new(());

/// A fresh hub state with the two nodes the workspace has, both online.
pub(crate) fn scratch(name: &str) {
    let dir = std::env::temp_dir().join(format!("midas-test-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_STATE", &dir) };
    for (id, machine, addr, port, gpu) in [("gpu-1", "laptop", "10.44.0.2", 2223, true), ("cpu-1", "server", "10.44.0.1", 2224, false)] {
        registry::add_node(&json!({"id": id, "machine": machine, "address": addr, "ssh_port": port, "gpu": gpu, "renderer": "test"})).unwrap();
        registry::set_online(id, true, "test").unwrap();
    }
}

fn claim(owner: &str, machine: &str, node: Option<&str>, queue: bool) -> bool {
    registry::claim(&Claim {
        owner: owner.into(), machine: machine.into(), node: node.map(str::to_string),
        branch: None, purpose: None, ttl: registry::DEFAULT_TTL, queue, mode: registry::Mode::Build, rank: None,
    }).unwrap().is_ok()
}

fn holder(node: &str) -> Option<String> {
    Locked::open().unwrap().leases().get(node).and_then(|l| l["owner"].as_str().map(str::to_string))
}

#[test]
fn a_free_node_goes_to_the_first_claim_and_only_to_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("first");
    assert!(claim("a", "server", None, false));
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
    assert!(!claim("b", "server", None, false), "the only server node is taken");
    assert!(claim("a", "server", None, false), "a holder asking again gets the same node back");
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
}

#[test]
fn the_longest_waiter_gets_a_freed_node_not_the_quickest_poller() {
    let _g = SERIAL.lock().unwrap();
    scratch("queue");
    assert!(claim("holder", "server", None, false));
    assert!(!claim("early", "server", None, true));
    std::thread::sleep(std::time::Duration::from_millis(1100)); // `since` is in seconds
    assert!(!claim("late", "server", None, true));
    registry::release("holder", None, false).unwrap();
    assert!(!claim("late", "server", None, true), "late asked first after the release, but early was in line first");
    assert!(!claim("warmer", "server", Some("cpu-1"), false), "an unqueued claimant is behind every waiter");
    assert!(claim("early", "server", None, true));
    assert_eq!(holder("cpu-1").as_deref(), Some("early"));
    assert!(registry::position("late").unwrap().contains("next in line"));
}

/// `midas run mac-1 -- …` (2026-11-15) queued for a *machine* called mac-1,
/// which no node is on: it waited three hours behind a deploy that had long
/// let the node go, while `midas status` showed it free.
#[test]
fn a_run_naming_a_node_gets_it_when_a_deploy_lets_it_go() {
    let _g = SERIAL.lock().unwrap();
    scratch("named-run");
    assert!(claim("deployer:mini", "any", Some("gpu-1"), false));
    let job = |owner: &str, machine: &str| registry::claim(&Claim {
        owner: owner.into(), machine: machine.into(), node: None, branch: None, purpose: None,
        ttl: registry::DEFAULT_TTL, queue: true, mode: registry::Mode::Job, rank: Some("bash bench.sh".into()),
    }).unwrap();
    let held = job("session-s693", "gpu-1").unwrap_err();
    assert_eq!(held["passed_over"][0]["why"], "held", "it waits for the node, not for nothing: {held}");
    assert_eq!(held["passed_over"].as_array().unwrap().len(), 1, "and only for that node: {held}");
    registry::release("deployer:mini", None, false).unwrap();
    assert_eq!(job("session-s693", "gpu-1").unwrap()["id"], "gpu-1", "the next poll, five seconds later, gets it");
    assert_eq!(holder("gpu-1").as_deref(), Some("session-s693"));
    // A name nothing goes by passes over no node, which the client takes as
    // "no node matches" and stops at once rather than waiting out a run's 30 days.
    assert!(job("lost", "mac-9").unwrap_err()["passed_over"].as_array().unwrap().is_empty());
}

#[test]
fn a_drained_node_is_handed_to_nobody_until_undrained() {
    let _g = SERIAL.lock().unwrap();
    scratch("drain");
    registry::drain("gpu-1", Some("testing"), "op").unwrap();
    assert!(!claim("a", "laptop", None, false));
    assert!(!claim("a", "any", Some("gpu-1"), false), "naming it does not get round the drain");
    registry::set_online("gpu-1", false, "test").unwrap();
    registry::set_online("gpu-1", true, "test").unwrap();
    assert!(!claim("a", "laptop", None, false), "a heartbeat coming back does not undo a drain");
    registry::drain("gpu-1", None, "op").unwrap();
    assert!(claim("a", "laptop", None, false));
}

#[test]
fn a_named_node_is_never_swapped_for_another() {
    let _g = SERIAL.lock().unwrap();
    scratch("named");
    assert!(claim("x", "any", Some("gpu-1"), false));
    assert!(!claim("y", "any", Some("gpu-1"), false), "gpu-1 is held; cpu-1 is free but was not asked for");
    assert_eq!(holder("cpu-1"), None);
}

#[test]
fn an_offline_node_is_skipped_and_gpu_means_any_gpu_node() {
    let _g = SERIAL.lock().unwrap();
    scratch("offline");
    registry::set_online("gpu-1", false, "test").unwrap();
    assert!(!claim("a", "gpu", None, false));
    assert!(claim("a", "any", None, false));
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
    registry::set_online("gpu-1", true, "test").unwrap();
    assert!(claim("b", "gpu", None, false));
    assert_eq!(holder("gpu-1").as_deref(), Some("b"));
}

#[test]
fn a_lease_nobody_renews_lapses_and_renewing_by_node_keeps_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("lapse");
    assert!(claim("gone", "server", None, false));
    let age = |t: i64| {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(t);
        reg.mark();
        reg.commit().unwrap();
    };
    age(registry::now() - registry::DEFAULT_TTL + 60);
    registry::renew(None, Some("cpu-1"), Some("cargo test")).unwrap();
    assert!(!claim("next", "server", None, false), "a node session renewed it");
    age(registry::now() - registry::DEFAULT_TTL - 1);
    assert!(claim("next", "server", None, false));
    assert_eq!(holder("cpu-1").as_deref(), Some("next"));
}

#[test]
fn a_hub_back_from_an_outage_keeps_the_leases_until_the_nodes_report() {
    let _g = SERIAL.lock().unwrap();
    scratch("outage");
    assert!(claim("a", "server", None, false));
    // The hub was down for three hours: no renewal, and the node's last reading,
    // from before, said nothing was open.
    let t = registry::now();
    registry::write_reading("cpu-1", &json!({"at": t - 3 * 3600, "sessions": 0, "heard_since": 0})).unwrap();
    {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(t - 3 * 3600);
        reg.mark();
        reg.commit().unwrap();
    }
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "a stale reading takes no lease away");
    // The node is heard again with nothing open: its holder may have built
    // through the outage and stopped a minute ago, so the half hour of quiet
    // counts from when the hub heard the node again.
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0})).unwrap();
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "heard for a moment is not quiet for half an hour");
    // Heard, and quiet, for longer than that: it lapses.
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0,
                                              "heard_since": registry::now() - registry::IDLE_S - 60})).unwrap();
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1"), None);
}

#[test]
fn nodes_are_data_added_and_removed_without_a_rebuild() {
    let _g = SERIAL.lock().unwrap();
    scratch("nodes");
    let n = json!({"id": "box-3", "machine": "box", "address": "10.44.0.3", "ssh_port": 2225, "gpu": true, "renderer": "t"});
    registry::add_node(&n).unwrap();
    assert!(registry::add_node(&n).is_err(), "the same id twice is refused");
    let mut same_place = n.clone();
    same_place["id"] = json!("box-4");
    assert!(registry::add_node(&same_place).is_err(), "so is another node's address and port");
    assert!(!claim("a", "box", None, false), "out of the pool until its first heartbeat");
    registry::set_online("box-3", true, "test").unwrap();
    assert!(claim("a", "box", None, false));
    assert!(registry::remove_node("box-3").is_err(), "a held node is not removed");
    registry::release("a", None, false).unwrap();
    registry::remove_node("box-3").unwrap();
    assert!(!registry::is_node("box-3"));
    let st = registry::snapshot().unwrap();
    assert!(st["nodes"].as_array().unwrap().iter().all(|s| s["id"] != "box-3"));
}

#[test]
fn a_reading_describes_process_memory_and_cache_apart() {
    let r = json!({"mem_used": 8u64 << 30, "mem_anon": 1u64 << 30, "mem_max": 9u64 << 30,
                   "disk_free": 64_000_000_000u64, "warm": "ec992a8d7104", "version": "abc", "at": registry::now()});
    let d = registry::describe_reading(&r);
    assert!(d.contains("memory 1.0 of 9.0 GiB (+7.0 cache)"), "{d}");
    assert!(d.contains("64 GB free") && d.contains("warm at ec992a8d") && d.contains("midas abc"), "{d}");
    let stale: Value = json!({"at": registry::now() - 600});
    assert!(registry::describe_reading(&stale).contains("node may be down"));
}

#[test]
fn an_event_sent_without_a_time_is_still_found() {
    let _g = SERIAL.lock().unwrap();
    scratch("record");
    crate::events::record(&json!({"kind": "ssh_session", "node": "gpu-1", "command": "cargo test"}));
    let found = crate::events::read_at(&registry::root(), &crate::events::Filter {
        since: chrono::Duration::minutes(5), kinds: vec!["ssh_session".into()], node: None, actor: None,
    });
    assert_eq!(found.len(), 1, "a node's event, which arrives with no ts, must not vanish from the log");
}

#[test]
fn every_node_has_a_uuid_of_its_own() {
    let _g = SERIAL.lock().unwrap();
    scratch("uuid");
    let u = registry::uuid_of("gpu-1").unwrap();
    assert!(registry::is_uuid(&u), "{u}");
    assert_ne!(Some(u.clone()), registry::uuid_of("cpu-1"), "each node its own");
    assert_eq!(registry::uuid_of("gpu-1"), Some(u), "and it does not change");
    assert_eq!(registry::uuid_of("nope"), None);
}

#[test]
fn a_configured_bot_gets_its_sign_in_and_voice_key_and_the_page_never_sees_them() {
    let _g = SERIAL.lock().unwrap();
    scratch("botconfig");
    use crate::botconfig::{env_for, overview, remove, set};
    set("scout", &json!({"server": "cartopolis.org", "username": "scout", "password": "hunter2"}), "web:sam").unwrap();
    let env = env_for("scout");
    assert_eq!(env.get("CARTO_SERVER").map(String::as_str), Some("cartopolis.org"));
    assert_eq!(env.get("CARTO_USER").map(String::as_str), Some("scout"));
    assert_eq!(env.get("CARTO_PASSWORD").map(String::as_str), Some("hunter2"));
    assert!(!env.contains_key("OPENAI_API_KEY"), "no voice, no key");

    // Its own key, with voice on; an empty password keeps the one there.
    set("scout", &json!({"voice": true, "openai_key": "sk-test-0123456789abcd", "password": ""}), "web:sam").unwrap();
    let env = env_for("scout");
    assert_eq!(env.get("OPENAI_API_KEY").map(String::as_str), Some("sk-test-0123456789abcd"));
    assert_eq!(env.get("CARTO_PASSWORD").map(String::as_str), Some("hunter2"));

    let page = overview().to_string();
    assert!(!page.contains("hunter2") && !page.contains("sk-test"), "no secret reaches the page: {page}");
    assert!(page.contains("\"ends\":\"abcd\"") && page.contains("\"password_set\":true"));
    let mode = std::fs::metadata(registry::root().join("bots.json")).unwrap().permissions();
    assert_eq!(std::os::unix::fs::PermissionsExt::mode(&mode) & 0o777, 0o600);

    assert!(set("bad name", &json!({}), "a").is_err());
    assert!(set("scout", &json!({"openai_key": "not-a-key"}), "a").is_err());
    assert!(set("scout", &json!({"server": "two words"}), "a").is_err());
    assert!(env_for("nobody").is_empty());

    // Start on the page: refused until it has all it needs, then taken by one
    // runner poll, once, with the command to run.
    let err = crate::botconfig::request("scout", "start", "web:sam").unwrap_err().to_string();
    assert!(err.contains("who it works for") && err.contains("a node"), "{err}");
    assert!(set("scout", &json!({"node": "nope"}), "a").is_err(), "an unknown node");
    set("scout", &json!({"works_for": "sam", "node": "gpu-1"}), "web:sam").unwrap();
    crate::botconfig::request("scout", "start", "web:sam").unwrap();
    let jobs = crate::botconfig::take_requests();
    assert_eq!(jobs.len(), 1);
    assert_eq!(jobs[0]["action"], "start");
    assert!(jobs[0]["args"].to_string().contains("--node\",\"gpu-1"));
    assert!(crate::botconfig::take_requests().is_empty(), "taken once");
    assert!(overview().to_string().contains("\"state\":\"starting\""));
    crate::botconfig::report("scout", "running", "running on gpu-1").unwrap();
    assert!(overview().to_string().contains("\"state\":\"running\""));
    assert!(crate::botconfig::report("scout", "bogus", "").is_err());

    assert!(remove("scout", "a").unwrap());
    assert!(env_for("scout").is_empty());
}

#[test]
fn bot_secrets_are_set_for_a_group_and_follow_a_node_through_a_rename() {
    let _g = SERIAL.lock().unwrap();
    scratch("botsecrets");
    let r = crate::botsecrets::set("gpu", "CARTO_TOKEN", Some("t0k"), "agents:wt").unwrap();
    assert_eq!(r["nodes"], json!(["gpu-1"]), "gpu names the GPU nodes");
    crate::botsecrets::set("any", "OTHER", Some("x"), "agents:wt").unwrap();
    assert_eq!(crate::botsecrets::for_node("gpu-1").get("CARTO_TOKEN").map(String::as_str), Some("t0k"));
    assert_eq!(crate::botsecrets::for_node("cpu-1").len(), 1, "cpu-1 got OTHER only");
    assert!(crate::botsecrets::set("gpu", "BAD NAME", Some("x"), "a").is_err());
    assert!(crate::botsecrets::set("gpu", "T", Some("two\nlines"), "a").is_err());
    assert!(crate::botsecrets::set("nope", "T", Some("x"), "a").is_err(), "names no node");
    assert!(!crate::botsecrets::names().to_string().contains("t0k"), "names, never values");
    let mode = std::fs::metadata(registry::root().join("bot-secrets.json")).unwrap().permissions();
    assert_eq!(std::os::unix::fs::PermissionsExt::mode(&mode) & 0o777, 0o600);

    registry::rename_node("gpu-1", "gpu-2").unwrap();
    assert_eq!(crate::botsecrets::for_node("gpu-2").get("CARTO_TOKEN").map(String::as_str), Some("t0k"), "a rename keeps them");
    assert!(crate::botsecrets::for_node("gpu-1").is_empty());
    crate::botsecrets::set("gpu-2", "CARTO_TOKEN", None, "a").unwrap();
    assert_eq!(crate::botsecrets::for_node("gpu-2").len(), 1, "removing one keeps the other");
    registry::remove_node("gpu-2").unwrap();
    assert!(crate::botsecrets::for_node("gpu-2").is_empty(), "a removed node's go with it");
}

#[test]
fn bot_secrets_set_at_once_from_many_connections_are_all_kept() {
    let _g = SERIAL.lock().unwrap();
    scratch("botsecrets-race");
    // The hub answers each connection on a thread of its own.
    let threads: Vec<_> = (0..8).map(|t| std::thread::spawn(move || {
        for i in 0..10 {
            crate::botsecrets::set("any", &format!("T{t}_{i}"), Some("x"), "agents:wt").unwrap();
        }
    })).collect();
    threads.into_iter().for_each(|t| t.join().unwrap());
    assert_eq!(crate::botsecrets::for_node("cpu-1").len(), 80, "no set lost to another");
    assert_eq!(crate::botsecrets::for_node("gpu-1").len(), 80);
}

#[test]
fn a_deploy_finds_the_latest_receipt_for_its_commit_and_only_for_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("verified");
    let (a, b) = ("0123456789abcdef0123456789abcdef01234567", "89abcdef0123456789abcdef0123456789abcdef");
    assert!(crate::deploy::verification(a).is_none());
    assert!(crate::deploy::record_verified("0123abcd", "agents:wt", &json!({})).is_err(), "a full sha");
    crate::deploy::record_verified(a, "agents:wt", &json!({"steps": "fmt test", "node": "vps-1"})).unwrap();
    crate::deploy::record_verified(a, "agents:wt", &json!({"steps": "fmt test render", "node": "deck-1"})).unwrap();
    let r = crate::deploy::verification(a).unwrap();
    assert_eq!((r["node"].as_str(), r["steps"].as_str()), (Some("deck-1"), Some("fmt test render")), "the latest");
    assert!(crate::deploy::verification(b).is_none(), "a receipt is for its commit");
}

#[test]
fn a_node_is_sent_to_the_hub_at_the_address_it_reaches_it_at() {
    let _g = SERIAL.lock().unwrap();
    scratch("hub-url");
    assert_eq!(registry::hub_url_of("gpu-1"), None, "until it has said");
    registry::note_hub_url("gpu-1", "192.168.64.1:4791").unwrap();
    assert_eq!(registry::hub_url_of("gpu-1").as_deref(), Some("http://192.168.64.1:4791"), "a Mac VM, through its gateway");
    for junk in ["", "evil.example:80", "192.168.64.1", "1.2.3.4:80/x", "[::1]:4791"] {
        registry::note_hub_url("gpu-1", junk).unwrap();
        assert_eq!(registry::hub_url_of("gpu-1").as_deref(), Some("http://192.168.64.1:4791"), "{junk:?} is not an address");
    }
    registry::note_hub_url("nope", "10.44.0.1:4791").unwrap();
    assert_eq!(registry::hub_url_of("cpu-1"), None, "and only for the node that said it");
}

#[test]
fn a_renamed_node_is_the_same_node_under_another_name() {
    let _g = SERIAL.lock().unwrap();
    scratch("rename");
    let git = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICQYcHgKOM50OM4CRt2PVlouMbC3w7KFx8Th+xAkT1lV midas-node-gpu-1";
    let host = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINOd1OkY/Q0J3yBCeNfb67fVcf27pOvZvxNsENAv1lGY root@x";
    registry::register_node("gpu-1", "10.44.0.2", git, host).unwrap();
    registry::drain("gpu-1", Some("moving it"), "op").unwrap();
    registry::write_reading("gpu-1", &json!({"at": registry::now(), "warm": "abcdef0123"})).unwrap();
    let uuid = registry::uuid_of("gpu-1").unwrap();

    assert!(registry::rename_node("gpu-1", "cpu-1").is_err(), "not onto another node's name");
    assert!(registry::rename_node("gpu-1", "Deck 1").is_err(), "names are lowercase, digits and dashes");
    assert!(registry::rename_node("nope", "gpu-2").is_err());
    registry::drain("gpu-1", None, "op").unwrap();
    assert!(claim("a", "laptop", None, false));
    assert!(registry::rename_node("gpu-1", "gpu-2").is_err(), "not while it is held");
    registry::release("a", None, false).unwrap();
    registry::drain("gpu-1", Some("moving it"), "op").unwrap();

    registry::rename_node("gpu-1", "gpu-2").unwrap();
    assert!(!registry::is_node("gpu-1"));
    let n = registry::nodes().into_iter().find(|n| n["id"] == "gpu-2").unwrap();
    assert_eq!(n["uuid"], uuid.as_str(), "the same node");
    assert_eq!(n["former_names"], json!(["gpu-1"]), "which the machine finds it by");
    assert_eq!((n["ssh_port"].clone(), n["host_key"].is_string(), n["git_key"].is_string()), (json!(2223), true, true),
               "its port and keys, so an agent's known_hosts still holds");
    let st = registry::snapshot().unwrap();
    let s = st["nodes"].as_array().unwrap().iter().find(|s| s["id"] == "gpu-2").unwrap().clone();
    assert_eq!(s["enabled"], true, "its live flags");
    assert_eq!(s["drained"]["why"], "moving it");
    assert_eq!(s["reading"]["warm"], "abcdef0123", "and its last reading");
    assert!(registry::reading("gpu-1").is_none());

    // Renamed back, the old name is not listed as a former one of itself.
    registry::rename_node("gpu-2", "gpu-1").unwrap();
    let n = registry::nodes().into_iter().find(|n| n["id"] == "gpu-1").unwrap();
    assert_eq!((n["uuid"].as_str(), n["former_names"].clone()), (Some(uuid.as_str()), json!(["gpu-2"])));
}

#[test]
fn a_node_registers_its_keys_only_from_its_own_address() {
    let _g = SERIAL.lock().unwrap();
    scratch("register");
    let git = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICQYcHgKOM50OM4CRt2PVlouMbC3w7KFx8Th+xAkT1lV midas-node-gpu-1";
    let host = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINOd1OkY/Q0J3yBCeNfb67fVcf27pOvZvxNsENAv1lGY root@x";
    assert!(registry::register_node("gpu-1", "10.44.0.1", git, host).is_err(), "cpu-1's address cannot speak for gpu-1");
    assert!(registry::register_node("gpu-1", "10.44.0.2", "not a key", host).is_err());
    assert!(registry::register_node("gpu-1", "10.44.0.2", git, host).unwrap());
    assert!(!registry::register_node("gpu-1", "10.44.0.2", git, host).unwrap(), "the same keys again change nothing");
    let n = registry::nodes().into_iter().find(|n| n["id"] == "gpu-1").unwrap();
    assert_eq!(n["git_key"], git.rsplit_once(' ').unwrap().0, "stored without the comment");
    // What an agent's ssh trusts comes from here.
    let kh = crate::sshcfg::known_hosts(&registry::nodes());
    assert_eq!(kh, format!("[10.44.0.2]:2223 {}\n", host.rsplit_once(' ').unwrap().0));
    let cfg = crate::sshcfg::block_for(&registry::nodes(), &crate::sshcfg::Opts {
        identity: "k".into(), known_hosts: "kh".into(), flush: false, write: None,
    });
    assert!(cfg.contains("Host gpu-1\n    HostName 10.44.0.2\n    Port 2223"));
    assert!(cfg.contains("StrictHostKeyChecking yes"), "a registered host key is checked strictly");
    assert!(cfg.contains("StrictHostKeyChecking accept-new"), "cpu-1 has not registered yet");
}

#[test]
fn an_idle_lease_is_given_back_but_an_open_session_keeps_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("idle");
    assert!(claim("a", "server", None, false));
    let backdate = |secs: i64| {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(registry::now() - secs);
        reg.mark();
        reg.commit().unwrap();
    };
    // An older node that reports no session count is left alone.
    backdate(registry::IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
    // A session open on the node: still in use, however long ago it started.
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 1})).unwrap();
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
    // Nothing open, and not for half an hour: given back — heard all along.
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0, "heard_since": 0})).unwrap();
    backdate(registry::IDLE_S - 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "not yet half an hour");
    backdate(registry::IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1"), None);
}

#[test]
fn a_new_node_gets_the_next_free_port_on_its_machine() {
    let _g = SERIAL.lock().unwrap();
    scratch("ports");
    registry::add_node(&json!({"id": "a-1", "machine": "a", "address": "10.9.0.7", "gpu": false, "renderer": "t"})).unwrap();
    registry::add_node(&json!({"id": "a-2", "machine": "a", "address": "10.9.0.7", "gpu": false, "renderer": "t"})).unwrap();
    registry::add_node(&json!({"id": "b-1", "machine": "b", "address": "10.9.0.8", "gpu": false, "renderer": "t"})).unwrap();
    let port = |id: &str| registry::nodes().into_iter().find(|n| n["id"] == id).unwrap()["ssh_port"].as_u64();
    assert_eq!((port("a-1"), port("a-2"), port("b-1")), (Some(2223), Some(2224), Some(2223)));
}

fn claim_as(owner: &str, node: &str, mode: registry::Mode) -> bool {
    registry::claim(&Claim {
        owner: owner.into(), machine: "any".into(), node: Some(node.into()),
        branch: None, purpose: Some("talking to it".into()), ttl: registry::DEFAULT_TTL, queue: false, mode, rank: None,
    }).unwrap().is_ok()
}

fn mode(node: &str) -> registry::Mode {
    registry::mode_of(&Locked::open().unwrap().leases()[node])
}

#[test]
fn a_lease_is_for_building_unless_it_says_bot() {
    let _g = SERIAL.lock().unwrap();
    scratch("mode");
    assert!(claim("a", "server", None, false));
    assert_eq!(mode("cpu-1"), registry::Mode::Build, "every caller from before modes gets a build lease");
    assert!(claim_as("b", "gpu-1", registry::Mode::Bot));
    assert_eq!(mode("gpu-1"), registry::Mode::Bot);
    let st = registry::snapshot().unwrap();
    assert_eq!(st["leases"]["gpu-1"]["mode"], "bot", "status --json says so");
    // Building on a node and then running a bot there is one lease; a `take`
    // from a bot's holder leaves its bot alone.
    assert!(claim_as("a", "cpu-1", registry::Mode::Bot));
    assert_eq!(mode("cpu-1"), registry::Mode::Bot);
    assert!(claim_as("a", "cpu-1", registry::Mode::Build));
    assert_eq!(mode("cpu-1"), registry::Mode::Bot);
    assert!(registry::Mode::parse(Some("party")).is_err());
}

#[test]
fn a_job_lease_goes_a_minute_after_its_run_when_somebody_waits_and_ten_when_nobody_does() {
    let _g = SERIAL.lock().unwrap();
    scratch("job");
    assert!(claim_as("a", "cpu-1", registry::Mode::Job));
    assert_eq!(mode("cpu-1"), registry::Mode::Job);
    let quiet_for = |secs: i64| {
        {
            let mut reg = Locked::open().unwrap();
            reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(registry::now() - secs);
            reg.mark();
            reg.commit().unwrap();
        }
        registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0, "heard_since": 0})).unwrap();
        registry::snapshot().unwrap();
    };
    quiet_for(registry::JOB_WAITED_IDLE_S + 30);
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "nobody waits: kept for its holder's next run");
    assert!(!claim("b", "server", None, true));
    quiet_for(registry::JOB_WAITED_IDLE_S - 30);
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "room for an scp straight after the run");
    quiet_for(registry::JOB_WAITED_IDLE_S + 30);
    assert_eq!(holder("cpu-1"), None, "somebody waits: a minute after the run, not twenty");
    assert!(claim("b", "server", None, true));
    registry::release("b", None, false).unwrap();
    assert!(claim_as("a", "cpu-1", registry::Mode::Job));
    quiet_for(registry::JOB_IDLE_S + 30);
    assert_eq!(holder("cpu-1"), None, "nobody waits: ten minutes");
}

#[test]
fn a_take_makes_a_job_lease_a_build_lease_and_a_run_leaves_a_lease_as_it_is() {
    let _g = SERIAL.lock().unwrap();
    scratch("job-mode");
    assert!(claim_as("a", "cpu-1", registry::Mode::Job));
    assert!(claim_as("a", "cpu-1", registry::Mode::Build));
    assert_eq!(mode("cpu-1"), registry::Mode::Build);
    assert!(claim_as("a", "cpu-1", registry::Mode::Job));
    assert_eq!(mode("cpu-1"), registry::Mode::Build, "a run on a node held for building leaves it held");
    assert!(claim_as("b", "gpu-1", registry::Mode::Bot));
    assert!(claim_as("b", "gpu-1", registry::Mode::Job));
    assert_eq!(mode("gpu-1"), registry::Mode::Bot, "and a bot's");
}

#[test]
fn a_run_goes_back_to_the_node_it_left_when_that_is_as_fast_and_nobody_used_it_since() {
    let n = |id: &str, machine: &str| json!({"id": id, "machine": machine});
    let t = registry::now();
    let last = |pairs: &[(&str, &str, i64)]| -> serde_json::Map<String, Value> {
        pairs.iter().map(|(o, node, at)| (o.to_string(), json!({"node": node, "at": at}))).collect()
    };
    let order = |free: &[Value]| free.iter().map(|n| n["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();
    let mut free = vec![n("mac-1", "mini"), n("mac-2", "mini"), n("vps-1", "vps")];
    registry::prefer_last(&mut free, "a", &last(&[("a", "mac-2", t - 60)]), t);
    assert_eq!(order(&free), ["mac-2", "mac-1", "vps-1"]);
    let mut free = vec![n("mac-1", "mini"), n("vps-1", "vps")];
    registry::prefer_last(&mut free, "a", &last(&[("a", "vps-1", t - 60)]), t);
    assert_eq!(order(&free), ["mac-1", "vps-1"], "never a slower machine for it");
    let mut free = vec![n("mac-1", "mini"), n("mac-2", "mini")];
    registry::prefer_last(&mut free, "a", &last(&[("a", "mac-2", t - 120), ("b", "mac-2", t - 60)]), t);
    assert_eq!(order(&free), ["mac-1", "mac-2"], "b has been there since: a's tree is gone from it");
    let mut free = vec![n("mac-1", "mini"), n("mac-2", "mini")];
    registry::prefer_last(&mut free, "a", &last(&[("a", "mac-2", t - registry::AFFINITY_S - 1)]), t);
    assert_eq!(order(&free), ["mac-1", "mac-2"], "forgotten after a day");
}

#[test]
fn status_tells_a_bot_from_a_build() {
    let build = json!({"owner": "wt-1", "purpose": "tests"});
    let bot = json!({"owner": "wt-2", "purpose": "exploring", "mode": "bot"});
    assert_eq!(crate::cli::holding(&build), "held by wt-1 — tests");
    assert_eq!(crate::cli::holding(&bot), "bot, held by wt-2 — exploring");
    let r = json!({"at": registry::now(), "bot": {"running": true, "since": registry::now() - 600, "command": "cargo run -q"}});
    assert!(registry::describe_reading(&r).contains("bot up 10m: cargo run -q"), "{}", registry::describe_reading(&r));
}

#[test]
fn a_running_bot_keeps_a_bot_lease_and_only_a_bot_lease() {
    let _g = SERIAL.lock().unwrap();
    scratch("bot-renews");
    assert!(claim_as("bot", "gpu-1", registry::Mode::Bot));
    assert!(claim_as("build", "cpu-1", registry::Mode::Build));
    let running = json!({"sessions": 0, "bot": {"running": true, "since": 1, "command": "x"}});
    let backdate = |node: &str| {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut(node).unwrap()["renewed_at"] = json!(registry::now() - registry::IDLE_S - 60);
        reg.mark();
        reg.commit().unwrap();
    };
    for node in ["gpu-1", "cpu-1"] {
        backdate(node);
        registry::write_reading(node, &json!({"at": registry::now(), "sessions": 0, "bot": running["bot"], "heard_since": 0})).unwrap();
    }
    // The heartbeat renews a bot lease whose bot runs; a bot under a build lease
    // keeps nothing alive (its node stops it).
    assert!(registry::renew_if_in_use("gpu-1", &running).unwrap());
    assert!(!registry::renew_if_in_use("cpu-1", &running).unwrap());
    // And the idle rule agrees, even before a renewal lands.
    backdate("gpu-1");
    registry::snapshot().unwrap();
    assert_eq!(holder("gpu-1").as_deref(), Some("bot"), "a running bot is a lease in use");
    assert_eq!(holder("cpu-1"), None, "no session and no bot of its own: given back");
    // The bot gone, the bot lease idles out like any other, counted from the
    // holder's last contact.
    registry::write_reading("gpu-1", &json!({"at": registry::now(), "sessions": 0, "bot": null, "heard_since": 0})).unwrap();
    assert!(!registry::renew_if_in_use("gpu-1", &json!({"sessions": 0, "bot": null})).unwrap());
    registry::snapshot().unwrap();
    assert_eq!(holder("gpu-1").as_deref(), Some("bot"), "its holder was here a moment ago");
    backdate_contact("gpu-1", registry::IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("gpu-1"), None);
}

/// Move a lease's holder contact (its last command, session and renewal) back.
fn backdate_contact(node: &str, by: i64) {
    let mut reg = Locked::open().unwrap();
    let l = reg.leases_mut().get_mut(node).unwrap();
    let then = json!(registry::now() - by);
    l["last_active"] = then.clone();
    l["contact_at"] = then;
    reg.mark();
    reg.commit().unwrap();
}

#[test]
fn a_running_bot_nobody_talks_to_gives_its_lease_back() {
    let _g = SERIAL.lock().unwrap();
    scratch("bot-orphaned");
    assert!(claim_as("bot", "gpu-1", registry::Mode::Bot));
    let running = json!({"at": registry::now(), "sessions": 0, "bot": {"running": true, "since": 1, "command": "x"}, "heard_since": 0});
    registry::write_reading("gpu-1", &running).unwrap();
    // Its holder's session ended: the heartbeat kept renewing the lease, so the
    // renewal is recent, but nobody has been in touch for half an hour.
    backdate_contact("gpu-1", registry::IDLE_S + 60);
    assert!(!registry::renew_if_in_use("gpu-1", &running).unwrap(), "a bot alone is not a lease in use");
    registry::snapshot().unwrap();
    assert_eq!(holder("gpu-1"), None, "given back, and its node stops the bot");

    // An ssh session open to it (a long wait on the bot) is contact: it keeps
    // the lease past the half hour, and after it closes the bot runs on.
    assert!(claim_as("bot", "gpu-1", registry::Mode::Bot));
    backdate_contact("gpu-1", registry::IDLE_S + 60);
    let talking = json!({"at": registry::now(), "sessions": 1, "bot": running["bot"]});
    registry::write_reading("gpu-1", &talking).unwrap();
    assert!(registry::renew_if_in_use("gpu-1", &talking).unwrap());
    registry::write_reading("gpu-1", &running).unwrap();
    assert!(registry::renew_if_in_use("gpu-1", &running).unwrap(), "the session just ended: still in touch");
    registry::snapshot().unwrap();
    assert_eq!(holder("gpu-1").as_deref(), Some("bot"));

    // The holder asking to renew is contact too.
    backdate_contact("gpu-1", registry::IDLE_S - 60);
    registry::renew(Some("bot"), None, None).unwrap();
    let contact = Locked::open().unwrap().leases()["gpu-1"]["contact_at"].as_i64().unwrap();
    assert!(registry::now() - contact < 5, "renewing by owner did not count as contact");
}

fn land(owner: &str) -> bool {
    registry::land_claim(owner, Some(&format!("branch-{owner}")), None).unwrap().is_ok()
}

fn landing_holder() -> Option<String> {
    Locked::open().unwrap().state["landing"]["holder"]["owner"].as_str().map(str::to_string)
}

#[test]
fn landings_take_turns_in_the_order_they_asked() {
    let _g = SERIAL.lock().unwrap();
    scratch("land-order");
    assert!(land("a"), "nobody is landing: the first to ask lands");
    assert!(!land("b"));
    std::thread::sleep(std::time::Duration::from_millis(1100)); // `since` is in seconds
    assert!(!land("c"));
    assert!(land("a"), "the holder asking again keeps its turn");
    assert!(registry::land_renew("a", Some("gating")).unwrap());
    assert!(!registry::land_renew("b", None).unwrap(), "only the holder renews");
    assert!(registry::land_release("a", Some("landed"), None).unwrap());
    assert!(!land("c"), "c asked first after the release, but b was in line first");
    assert!(land("b"));
    assert_eq!(landing_holder().as_deref(), Some("b"));
}

#[test]
fn a_landing_in_progress_is_never_overtaken_and_a_dead_one_lapses() {
    let _g = SERIAL.lock().unwrap();
    scratch("land-lapse");
    assert!(land("a"));
    for _ in 0..3 {
        assert!(!land("b"), "a newer landing waits however often it asks");
    }
    // `a` dies without releasing: its turn lapses after LAND_TTL silent seconds.
    {
        let mut reg = Locked::open().unwrap();
        reg.state["landing"]["holder"]["renewed_at"] = json!(registry::now() - registry::LAND_TTL - 1);
        reg.mark();
        reg.commit().unwrap();
    }
    assert!(land("b"), "the next in line goes");
    assert_eq!(landing_holder().as_deref(), Some("b"));
}

#[test]
fn giving_up_a_place_in_line_lets_the_next_one_land() {
    let _g = SERIAL.lock().unwrap();
    scratch("land-give-up");
    assert!(land("a"));
    assert!(!land("b"));
    std::thread::sleep(std::time::Duration::from_millis(1100));
    assert!(!land("c"));
    assert!(registry::land_release("b", Some("abandoned"), None).unwrap(), "a place in line can be given back");
    registry::land_release("a", Some("landed"), None).unwrap();
    assert!(land("c"));
}

#[test]
fn a_ranked_take_goes_to_the_fastest_free_node() {
    let _g = SERIAL.lock().unwrap();
    scratch("rank");
    for (id, machine, port) in [("slow-1", "vps", 2230), ("fast-1", "mini", 2231), ("fast-2", "mini", 2232)] {
        registry::add_node(&json!({"id": id, "machine": machine, "address": "10.44.0.9", "ssh_port": port, "gpu": false, "renderer": "test"})).unwrap();
        registry::set_online(id, true, "test").unwrap();
    }
    let gate = ".claude/skills/finish-branch/verify-branch";
    let now = chrono::Utc::now().to_rfc3339();
    let mut lines = String::new();
    for (node, machine, seconds, exit) in [
        ("slow-1", "vps", 900, 0), ("slow-1", "vps", 870, 0),
        ("fast-1", "mini", 460, 0), ("fast-1", "mini", 5, 1), // a red run says nothing about speed
        ("cpu-1", "server", 30, 0),                            // a different command
    ] {
        let shape = if node == "cpu-1" { "cargo check" } else { gate };
        lines += &format!("{}\n", json!({"ts": now, "node": node, "machine": machine, "shape": shape, "seconds": seconds, "exit": exit}));
    }
    std::fs::write(registry::root().join("builds.jsonl"), lines).unwrap();
    // The gate as finish-branch passes it: the whole command line, which the
    // history records shortened.
    let command = format!("CARTO_GATE_NO_SLOT=1 {gate} --base \"$MIDAS_BASE\"");
    let take = |owner: &str| registry::claim(&Claim {
        owner: owner.into(), machine: "any".into(), node: None, branch: None, purpose: None,
        ttl: registry::DEFAULT_TTL, queue: false, mode: registry::Mode::Build, rank: Some(command.clone()),
    }).unwrap().unwrap()["id"].as_str().unwrap().to_string();
    assert_eq!(take("a"), "fast-1");
    assert_eq!(take("b"), "fast-2", "no runs of its own: its machine's");
    assert_eq!(take("c"), "slow-1");
    assert_eq!(take("d"), "cpu-1", "unmeasured, but no GPU");
    assert_eq!(take("e"), "gpu-1");
    assert!(claim("f", "any", None, false) == false, "all taken");
}

#[test]
fn an_unranked_take_between_equals_leaves_the_gpu_node_for_last() {
    let _g = SERIAL.lock().unwrap();
    scratch("unranked");
    // gpu-1 is listed first; with no build history either is as fast, and the
    // GPU node is kept for what needs one.
    assert!(claim("a", "any", None, false));
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
    assert!(claim("b", "any", None, false));
    assert_eq!(holder("gpu-1").as_deref(), Some("b"));
}

#[test]
fn a_fast_node_new_to_a_command_goes_before_a_slow_one_that_ran_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("rank-new");
    registry::add_node(&json!({"id": "mac-1", "machine": "mini", "address": "10.44.0.9", "ssh_port": 2231, "gpu": false, "renderer": "test"})).unwrap();
    registry::set_online("mac-1", true, "test").unwrap();
    let ts = chrono::Utc::now().to_rfc3339();
    let mut lines = String::new();
    // In general the mini builds in a third of the time; only cpu-1 ever ran the
    // gate — and the cold first build of a lease, five times slower, says nothing.
    for (node, machine, shape, secs, first) in [
        ("cpu-1", "server", "cargo test", 600, false), ("cpu-1", "server", "cargo test", 640, false),
        ("mac-1", "mini", "cargo test", 200, false), ("mac-1", "mini", "cargo test", 220, false),
        ("cpu-1", "server", "tools/verify-branch", 300, false), ("cpu-1", "server", "tools/verify-branch", 320, false),
        ("mac-1", "mini", "tools/verify-branch", 1500, true),
    ] {
        lines += &format!("{}\n", json!({"ts": ts, "node": node, "machine": machine, "actor": "s", "shape": shape,
            "seconds": secs, "exit": 0, "first_build_in_lease": first}));
    }
    std::fs::write(registry::root().join("builds.jsonl"), lines).unwrap();
    let take = |owner: &str| registry::claim(&Claim {
        owner: owner.into(), machine: "any".into(), node: None, branch: None, purpose: None,
        ttl: registry::DEFAULT_TTL, queue: false, mode: registry::Mode::Build,
        rank: Some("CARTO_GATE_NO_SLOT=1 tools/verify-branch --base \"$MIDAS_BASE\"".into()),
    }).unwrap().unwrap()["id"].as_str().unwrap().to_string();
    assert_eq!(take("a"), "mac-1");
    assert_eq!(take("b"), "cpu-1");
    assert_eq!(take("c"), "gpu-1");
}

// ── Sessions working together (collab.rs) ────────────────────────────────────

#[test]
fn a_note_reaches_its_session_once() {
    let _g = SERIAL.lock().unwrap();
    scratch("notes");
    crate::collab::say("a", "b", "can you yield after this build?", "say").unwrap();
    crate::collab::say("hub", "gate-b", "the gate's own note", "nudge").unwrap();
    let got = crate::collab::take_notes("b").unwrap();
    assert_eq!(got.len(), 2, "the gate's notes are the session's too");
    assert_eq!(got[0]["from"], "a");
    assert!(crate::collab::take_notes("b").unwrap().is_empty(), "taken means gone");
    assert!(crate::collab::say("a", "", "x", "say").is_err());
}

#[test]
fn a_hooks_notes_are_read_once_it_says_it_printed_them() {
    let _g = SERIAL.lock().unwrap();
    scratch("notes-hold");
    let one = crate::collab::say("a", "b", "first", "say").unwrap();
    crate::collab::say("hub", "gate-b", "the gate's", "nudge").unwrap();
    let held = crate::collab::hold_notes("b").unwrap();
    assert_eq!(held.len(), 2);
    assert!(crate::collab::hold_notes("b").unwrap().is_empty(), "a hook beside it does not print them again");
    assert_eq!(crate::collab::peek_notes("b").len(), 2, "unread until confirmed");
    assert_eq!(crate::collab::confirm_notes("b", &[one.clone()]).unwrap(), 1);
    assert_eq!(crate::collab::sent_by("a")[0]["state"], "read");
    // A hook that gave up before it confirmed: the other comes again a minute later.
    let path = crate::registry::root().join("collab.json");
    let mut c: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    c["notes"]["gate-b"][0]["held_at"] = json!(crate::registry::now() - 61);
    std::fs::write(&path, c.to_string()).unwrap();
    let again = crate::collab::hold_notes("b").unwrap();
    assert_eq!(again.len(), 1);
    assert_eq!(again[0]["text"], "the gate's");
    crate::collab::confirm_notes("b", &[again[0]["id"].as_str().unwrap().to_string()]).unwrap();
    assert!(crate::collab::peek_notes("b").is_empty());
}

#[test]
fn two_sessions_changing_the_same_file_both_hear_of_it_once() {
    let _g = SERIAL.lock().unwrap();
    scratch("overlap");
    let files = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
    crate::collab::report_work("a", Some("feat/a"), &files(&["src/x.rs", "Cargo.lock"])).unwrap();
    let found = crate::collab::report_work("b", Some("feat/b"), &files(&["src/x.rs", "src/y.rs", "Cargo.lock"])).unwrap();
    assert_eq!(found, vec![json!({"with": "a", "files": ["src/x.rs"]})], "Cargo.lock is everybody's");
    let a = crate::collab::take_notes("a").unwrap();
    let b = crate::collab::take_notes("b").unwrap();
    assert_eq!((a.len(), b.len()), (1, 1));
    assert!(a[0]["text"].as_str().unwrap().contains("b (feat/b) also changes 1 file you change:\n  src/x.rs"), "{}", a[0]["text"]);
    // The same overlap again is no news; a new shared file is.
    crate::collab::report_work("a", Some("feat/a"), &files(&["src/x.rs"])).unwrap();
    assert!(crate::collab::take_notes("b").unwrap().is_empty());
    crate::collab::report_work("a", Some("feat/a"), &files(&["src/x.rs", "src/y.rs"])).unwrap();
    assert_eq!(crate::collab::take_notes("b").unwrap().len(), 1);
    // Landed work overlaps nobody.
    crate::collab::landed("a", None, None);
    assert!(crate::collab::report_work("b", Some("feat/b"), &files(&["src/x.rs"])).unwrap().is_empty());
}

#[test]
fn reserved_numbers_are_never_handed_out_twice() {
    let _g = SERIAL.lock().unwrap();
    scratch("reserve");
    assert_eq!(crate::collab::reserve("migration", "a", 41, None).unwrap(), 42);
    assert_eq!(crate::collab::reserve("migration", "b", 41, Some("chat rooms")).unwrap(), 43, "b's main is as old as a's");
    assert_eq!(crate::collab::reserve("migration", "c", 50, None).unwrap(), 51, "a newer main wins");
    assert_eq!(crate::collab::reserve("wire-kind", "a", 7, None).unwrap(), 8, "namespaces are apart");
    assert!(crate::collab::reserve("Bad Name", "a", 0, None).is_err());
    assert_eq!(crate::collab::reservations()["migration"]["by"]["43"]["owner"], "b");
}

#[test]
fn a_yield_gives_the_node_back_when_the_build_ends() {
    let _g = SERIAL.lock().unwrap();
    scratch("yield");
    assert!(claim("a", "server", None, false));
    // A session is open on the node: the yield waits for it.
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 1})).unwrap();
    assert_eq!(registry::set_yield("a", true).unwrap(), Some(("cpu-1".into(), false)));
    assert_eq!(holder("cpu-1").as_deref(), Some("a"));
    assert!(!claim("b", "server", None, true));
    let pos = registry::position("b").unwrap();
    assert!(pos.contains("yielding after its build"), "{pos}");
    registry::session_closed_on("cpu-1").unwrap();
    assert_eq!(holder("cpu-1"), None);
    assert!(crate::collab::take_notes("a").unwrap()[0]["text"].as_str().unwrap().contains("went back"));
    // With nothing open, a yield is a release.
    assert!(claim("b", "server", None, true));
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0})).unwrap();
    assert_eq!(registry::set_yield("b", true).unwrap(), Some(("cpu-1".into(), true)));
    assert_eq!(holder("cpu-1"), None);
}

#[test]
fn a_waiter_sees_what_the_holder_said_it_is_doing() {
    let _g = SERIAL.lock().unwrap();
    scratch("intent");
    assert!(claim("a", "server", None, false));
    registry::set_intent("a", Some("cargo test --workspace"), Some(20)).unwrap();
    assert!(!claim("b", "server", None, true));
    let pos = registry::position("b").unwrap();
    assert!(pos.contains("(\"cargo test --workspace\", about 20m more)"), "{pos}");
    registry::set_intent("a", None, None).unwrap();
    assert!(!registry::position("b").unwrap().contains("cargo test"));
    assert_eq!(registry::set_intent("nobody", Some("x"), None).unwrap(), None);
}

#[test]
fn an_unused_node_somebody_waits_for_nudges_its_holder() {
    let _g = SERIAL.lock().unwrap();
    scratch("nudge");
    assert!(claim("a", "server", None, false));
    assert!(!claim("b", "server", None, true));
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0})).unwrap();
    // Quiet for twenty minutes.
    {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["last_active"] = json!(registry::now() - 1200);
        reg.mark();
        reg.commit().unwrap();
    }
    crate::collab::nudge_idle_holders();
    let notes = crate::collab::take_notes("a").unwrap();
    assert_eq!(notes.len(), 1);
    assert!(notes[0]["text"].as_str().unwrap().starts_with("1 waiting for cpu-1"), "{}", notes[0]["text"]);
    crate::collab::nudge_idle_holders();
    assert!(crate::collab::take_notes("a").unwrap().is_empty(), "not again within the quarter hour");
}

#[test]
fn a_take_naming_no_command_gets_the_fastest_free_node() {
    let _g = SERIAL.lock().unwrap();
    scratch("fastest");
    registry::add_node(&json!({"id": "mac-1", "machine": "mini", "address": "10.44.0.3", "ssh_port": 2225, "gpu": false, "renderer": "test"})).unwrap();
    registry::set_online("mac-1", true, "test").unwrap();
    // cpu-1 is listed first, but the mini builds in a third of the time.
    let ts = chrono::Utc::now().to_rfc3339();
    let mut lines = String::new();
    for (node, machine, secs) in [("cpu-1", "server", 600), ("cpu-1", "server", 640), ("mac-1", "mini", 200), ("mac-1", "mini", 220)] {
        lines += &format!("{}\n", json!({"ts": ts, "node": node, "machine": machine, "actor": "s", "shape": "cargo test",
            "seconds": secs, "exit": 0, "first_build_in_lease": false}));
    }
    std::fs::write(registry::root().join("builds.jsonl"), lines).unwrap();
    let (_, machines) = crate::builds::speed_factors(86400);
    assert!(machines["mini"] < 1.0 && machines["server"] > 1.0, "{machines:?}");
    assert!(claim("a", "any", None, false));
    assert_eq!(holder("mac-1").as_deref(), Some("a"), "the fastest free node, not the first listed");
    assert!(claim("b", "any", None, false));
    assert_eq!(holder("cpu-1").as_deref(), Some("b"), "then the next fastest; the unmeasured GPU node last");
}

#[test]
fn an_open_end_goes_to_the_first_session_on_its_machine_and_stays_with_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("todos");
    let id = crate::collab::todo_add("agent:s1", "workstation", "update midas and install its hooks").unwrap();
    crate::collab::todo_add("agent:s1", "any", "tell sam the page moved").unwrap();
    assert!(crate::collab::todo_add("agent:s1", "Work Station", "x").is_err());
    // The agent container's next session sees only what is for anyone.
    assert_eq!(crate::collab::todo_take("agent", "a1").unwrap().len(), 1);
    // The workstation's first session gets its own; a second session there does not.
    let w = crate::collab::todo_take("workstation", "w1").unwrap();
    assert_eq!(w.iter().map(|t| t["id"].as_str().unwrap()).collect::<Vec<_>>(), vec![id.as_str()]);
    assert!(crate::collab::todo_take("workstation", "w2").unwrap().is_empty());
    assert_eq!(crate::collab::todo_take("workstation", "w1").unwrap().len(), 1, "until done, its session sees it again");
    assert!(crate::collab::todo_context(&w).unwrap().contains("do these first"));
    crate::collab::todo_done(&id, "workstation:w1", Some("updated to f911803")).unwrap();
    assert!(crate::collab::todo_take("workstation", "w1").unwrap().is_empty());
    assert_eq!(crate::collab::todos().as_array().unwrap().len(), 2, "done ones stay a week");
    assert!(crate::collab::todo_done("t99", "x", None).is_err());
}

fn notes_for(owner: &str) -> Vec<String> {
    crate::collab::take_notes(owner).unwrap().iter().filter_map(|n| n["text"].as_str().map(str::to_string)).collect()
}

#[test]
fn a_next_turn_goes_to_its_claimant_ahead_of_the_line_and_is_used_up() {
    let _g = SERIAL.lock().unwrap();
    scratch("next");
    assert!(claim("holder", "server", None, false));
    assert!(!claim("early", "server", None, true), "in line first");
    assert_eq!(registry::reserve_next("cpu-1", "fixer", "midas update").unwrap().as_deref(), Some("holder"));
    assert!(registry::reserve_next("cpu-1", "other", "me too").is_err(), "one next turn at a time");
    assert!(registry::reserve_next("cpu-1", "holder", "x").is_err(), "the holder has it already");
    assert!(!claim("fixer", "any", Some("cpu-1"), true), "the holder keeps it meanwhile");
    assert!(registry::position("fixer").unwrap().contains("next in line"));
    registry::release("holder", None, false).unwrap();
    assert!(!claim("early", "server", None, true), "in line first, but it is somebody's next turn");
    assert!(claim("fixer", "any", Some("cpu-1"), true));
    assert_eq!(holder("cpu-1").as_deref(), Some("fixer"));
    registry::release("fixer", None, false).unwrap();
    assert!(claim("early", "server", None, true), "taking the turn used it up: no drain is left behind");
}

#[test]
fn a_next_turn_lapses_when_its_session_stops_waiting() {
    let _g = SERIAL.lock().unwrap();
    scratch("next-lapse");
    assert!(claim("holder", "server", None, false));
    registry::reserve_next("cpu-1", "gone", "never comes").unwrap();
    {
        let mut reg = Locked::open().unwrap();
        reg.node_mut("cpu-1").unwrap()["drained"]["at"] = json!(registry::now() - registry::WAITER_TTL - 1);
        reg.mark();
        reg.commit().unwrap();
    }
    registry::release("holder", None, false).unwrap();
    assert!(claim("someone", "server", None, false), "nobody waits for the turn, so the node is the pool's again");
}

#[test]
fn a_note_to_a_role_reaches_whoever_has_it_now() {
    let _g = SERIAL.lock().unwrap();
    scratch("roles");
    assert!(claim("a", "server", None, false));
    assert!(!claim("w", "server", None, true));
    crate::collab::report_work("x", Some("bx"), &["src/lib.rs".into(), "web/app.ts".into()]).unwrap();
    crate::collab::report_work("me", Some("bme"), &["src/lib.rs".into()]).unwrap();
    let _ = (notes_for("x"), notes_for("me"), notes_for("a"), notes_for("w")); // the overlap's own notes

    assert_eq!(said("me", "@cpu-1", "done soon?"), vec!["a"]);
    assert_eq!(notes_for("a"), vec!["(to @cpu-1) done soon?"]);
    assert_eq!(said("me", "@waiting:server", "a few minutes"), vec!["w"]);
    assert_eq!(said("me", "@file:src/lib.rs", "I rename foo"), vec!["x"], "not to the sender");
    assert_eq!(said("me", "@file:web/", "anything under it"), vec!["x"]);
    assert!(crate::collab::say_to("me", "@gpu-1", "nobody holds it", None).is_err());
    assert!(crate::collab::say_to("me", "@laptopp", "no such node", None).is_err());
    assert_eq!(said("me", "a", "plain"), vec!["a"]);
}

/// Who a note from a session went to.
fn said(from: &str, to: &str, text: &str) -> Vec<String> {
    crate::collab::say_to(from, to, text, None).unwrap().iter().filter_map(|n| n["to"].as_str().map(str::to_string)).collect()
}

/// The hub's own record of what passed between sessions.
fn collab_state() -> Value {
    serde_json::from_str(&std::fs::read_to_string(registry::root().join("collab.json")).unwrap()).unwrap()
}

fn set_collab_state(v: &Value) {
    std::fs::write(registry::root().join("collab.json"), v.to_string()).unwrap();
}

/// A session hook's mark, as if sent `ago_s` seconds ago.
fn mark(kind: &str, actor: &str, ago_s: i64, extra: Value) {
    let mut ev = extra;
    ev["kind"] = json!(kind);
    ev["actor"] = json!(actor);
    ev["ts"] = json!((chrono::Utc::now() - chrono::Duration::seconds(ago_s)).to_rfc3339());
    crate::events::record(&ev);
}

fn events_of(kind: &str) -> Vec<Value> {
    crate::events::read_at(&registry::root(), &crate::events::Filter {
        since: chrono::Duration::hours(1), kinds: vec![kind.into()], node: None, actor: None,
    })
}

#[test]
fn a_note_to_a_name_nobody_has_is_refused_with_the_closest_names() {
    let _g = SERIAL.lock().unwrap();
    scratch("unknown");
    mark("session_start", "bridge-cse_01JPKSiJRneMKLNc2MY29WPQ", 60, json!({"branch": "board-fix"}));
    mark("session_label", "bridge-cse_01JPKSiJRneMKLNc2MY29WPQ", 50, json!({"label": "fix the board"}));
    assert!(claim("readme-sheet", "server", None, false));
    // The branch name Claude Code gives a worktree is its session's.
    assert_eq!(said("me", "worktree-bridge-cse_01JPKSiJRneMKLNc2MY29WPQ", "hi"), vec!["bridge-cse_01JPKSiJRneMKLNc2MY29WPQ"]);
    assert_eq!(said("me", "board-fix", "by branch"), vec!["bridge-cse_01JPKSiJRneMKLNc2MY29WPQ"]);
    assert_eq!(said("me", "readme-sheet", "holding a node is being known"), vec!["readme-sheet"]);
    let e = crate::collab::say_to("me", "bridge-cse_01JPKSiJRneMKLNc2MY29WP", "a typo", None).unwrap_err();
    let u = e.downcast_ref::<crate::collab::Unknown>().expect("refused as unknown");
    assert_eq!(u.suggestions, vec!["bridge-cse_01JPKSiJRneMKLNc2MY29WPQ"]);
    assert!(u.error.contains("\"fix the board\"") && u.error.contains("midas who"), "{}", u.error);
    let far = crate::collab::say_to("me", "zzzz", "nobody", None).unwrap_err();
    assert!(far.downcast_ref::<crate::collab::Unknown>().unwrap().suggestions.is_empty());
    assert!(collab_state()["notes"]["zzzz"].is_null(), "nothing was left for a name nobody has");
    // A session whose end hook ran reads nothing more.
    mark("session_end", "bridge-cse_01JPKSiJRneMKLNc2MY29WPQ", 10, json!({"reason": "other"}));
    let ended = crate::collab::say_to("me", "bridge-cse_01JPKSiJRneMKLNc2MY29WPQ", "too late", None).unwrap_err();
    assert!(ended.to_string().contains("ended"), "{ended}");
}

#[test]
fn a_note_has_an_id_its_sender_sees_read_and_its_reader_answers() {
    let _g = SERIAL.lock().unwrap();
    scratch("receipts");
    mark("session_start", "a", 30, json!({"branch": "feat/a"}));
    mark("session_label", "a", 30, json!({"label": "routing"}));
    mark("session_start", "b", 30, json!({"branch": "feat/b"}));
    let sent = crate::collab::say_to("a", "b", "can you yield after this build?", None).unwrap();
    let id = sent[0]["id"].as_str().unwrap().to_string();
    assert!(id.starts_with('n'));
    assert_eq!(crate::collab::count_notes("b"), 1);
    assert_eq!(crate::collab::sent_by("a")[0]["state"], "waiting");
    let got = crate::collab::take_notes("b").unwrap();
    let line = crate::collab::note_line(&got[0]);
    assert_eq!(line, format!("midas: note {id} from a (\"routing\", feat/a): can you yield after this build? — reply: midas say --re {id} \"…\""));
    assert_eq!(crate::collab::sent_by("a")[0]["state"], "read");
    assert_eq!(events_of("note").last().unwrap()["id"], id.as_str());
    assert_eq!(events_of("notes_taken").last().unwrap()["ids"], json!([id]));
    // The answer goes to the sender, quoting what it answers.
    let back = crate::collab::say_to("b", "", "yes, in ten minutes", Some(&id)).unwrap();
    assert_eq!(back[0]["to"], "a");
    assert_eq!(notes_for("a"), vec![format!("(re {id} \"can you yield after this build?\") yes, in ten minutes")]);
    let hub = crate::collab::say("hub", "b", "an overlap", "overlap").unwrap();
    assert!(crate::collab::say_to("b", "", "thanks", Some(&hub)).is_err(), "midas reads no replies");
    assert!(crate::collab::say_to("b", "", "x", Some("n999")).is_err());
}

#[test]
fn notes_go_unread_when_their_session_ends_and_their_sender_hears_once() {
    let _g = SERIAL.lock().unwrap();
    scratch("expire");
    for o in ["a", "b", "c"] {
        mark("session_start", o, 30, json!({}));
    }
    said("a", "b", "first");
    said("a", "b", "second");
    said("c", "b", "from c");
    crate::collab::report_work("b", Some("feat/b"), &["src/x.rs".into()]).unwrap();
    // A /clear is the same worktree carrying on.
    mark("session_end", "b", 5, json!({"reason": "clear"}));
    assert_eq!(crate::collab::count_notes("b"), 3);
    mark("session_end", "b", 0, json!({"reason": "other"}));
    assert_eq!(crate::collab::count_notes("b"), 0, "its mailbox went with it");
    assert!(collab_state()["work"]["b"].is_null(), "and its work");
    let to_a = notes_for("a");
    assert_eq!(to_a.len(), 1, "one note per sender: {to_a:?}");
    assert!(to_a[0].starts_with("b ended before reading your note") && to_a[0].contains("\"first\"") && to_a[0].contains("\"second\""), "{}", to_a[0]);
    assert_eq!(notes_for("c").len(), 1);
    let expired = events_of("note_expired");
    assert_eq!(expired.len(), 3);
    assert!(expired.iter().all(|e| e["reason"] == "session_ended" && e["to"] == "b" && e["id"].is_string()));
    assert_eq!(crate::collab::sent_by("a")[0]["state"], "expired");

    // Two days unread is long enough, whoever it was for.
    said("a", "c", "old news");
    said("a", "c", "fresh");
    let mut st = collab_state();
    st["notes"]["c"][0]["ts"] = json!(registry::now() - 3 * 86400);
    set_collab_state(&st);
    crate::collab::expire_notes();
    assert_eq!(notes_for("c"), vec!["fresh"]);
    let told = notes_for("a");
    assert!(told.len() == 1 && told[0].contains("did not read your note") && told[0].contains("old news"), "{told:?}");
}

#[test]
fn an_idle_hosted_session_is_sent_the_note_and_a_remote_one_is_named() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("wake");
    let id = sessions::start("ana", "draw a cat", None, None, None, None, None, &Value::Null).unwrap();
    sessions::push(&id, &[], Some("waiting"), "runner@x", None, None).unwrap();
    let owner = format!("session-{id}");
    let sent = crate::collab::say_to("me", &owner, "the board is yours", None).unwrap();
    assert_eq!(sent[0]["woken"], true);
    let inbox = std::fs::read_to_string(registry::root().join("hosted").join(&id).join("inbox.jsonl")).unwrap();
    assert!(inbox.contains("the board is yours"), "{inbox}");
    assert_eq!(crate::collab::count_notes(&owner), 0, "read as a message, not again from the mailbox");
    // A Remote Control session last heard of twenty minutes ago looks idle.
    mark("session_start", "bridge-cse_01ABC", 1200, json!({}));
    let sent = crate::collab::say_to("me", "bridge-cse_01ABC", "are you there?", None).unwrap();
    assert_eq!(sent[0]["session"], "session_01ABC");
    assert!(sent[0]["idle_since"].as_i64().is_some_and(|t| registry::now() - t >= 1199));
    crate::collab::take_notes("bridge-cse_01ABC").unwrap();
    let sent = crate::collab::say_to("me", "bridge-cse_01ABC", "now it is here", None).unwrap();
    assert!(sent[0]["idle_since"].is_null(), "seen just now, at its hook");
}

#[test]
fn a_sessions_note_wakes_an_idle_editor_thread_midas_own_news_does_not() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("wake-mirrored");
    // A Zed thread mirrored to the page: named for its checkout, waiting for a prompt.
    let local = json!({"client": "Zed", "machine": "mini", "cwd": "/w/podium-x"});
    let id = sessions::attach("mini", "zed@mini", "3f4a74a9-0255-4b64-9bbf-66d74efa32c2", "talk", &local, Some("x"), "podium-x")
        .unwrap()["id"].as_str().unwrap().to_string();
    let inbox = || std::fs::read_to_string(registry::root().join("hosted").join(&id).join("inbox.jsonl")).unwrap_or_default();
    // Midas's own news waits for the next prompt: woken by it, the agent answered midas.
    crate::collab::say("hub", "podium-x", "The site deploy of 42c9efd0 you asked for is live.", "deploy").unwrap();
    crate::collab::say("hub", "podium-x", "b is also changing src/lib.rs", "overlap").unwrap();
    assert!(!inbox().contains("is live") && !inbox().contains("src/lib.rs"), "{}", inbox());
    assert_eq!(crate::collab::take_notes("podium-x").unwrap().len(), 2);
    // A session's note, and the person's answer to a decision, wake it.
    crate::collab::say("b", "podium-x", "can you take src/lib.rs?", "say").unwrap();
    assert!(inbox().contains("can you take src/lib.rs?"), "{}", inbox());
    assert_eq!(crate::collab::count_notes("podium-x"), 0, "read as a message");
    crate::collab::say("hub", "podium-x", "The person decided d1: yes", "decision").unwrap();
    assert!(inbox().contains("The person decided d1"), "{}", inbox());
    // Working: the note waits in the mailbox for its hooks instead.
    sessions::push(&id, &[], Some("working"), "zed@mini", None, None).unwrap();
    crate::collab::say("hub", "podium-x", "c waits for your node", "nudge").unwrap();
    assert_eq!(crate::collab::count_notes("podium-x"), 1);
    // Shown by hand (a subagent's `midas notes`), it stays for the session's hook.
    assert_eq!(crate::collab::peek_notes("podium-x").len(), 1);
    assert_eq!(crate::collab::count_notes("podium-x"), 1);
    assert_eq!(crate::collab::take_notes("podium-x").unwrap().len(), 1);
    assert_eq!(crate::collab::count_notes("podium-x"), 0);
}

#[test]
fn who_knows_the_node_each_session_holds_and_when_it_was_seen() {
    let _g = SERIAL.lock().unwrap();
    scratch("who");
    assert!(claim("a", "server", None, false));
    registry::set_intent("a", Some("cargo test"), Some(20)).unwrap();
    assert!(!claim("b", "server", None, true));
    crate::collab::take_notes("c").unwrap();
    let names = crate::collab::names();
    assert_eq!((names["a"]["node"].as_str(), names["a"]["intent"].as_str()), (Some("cpu-1"), Some("cargo test")));
    assert_eq!(names["b"]["waiting_for"], "server");
    assert!(names["c"]["seen"].as_i64().is_some_and(|t| registry::now() - t < 5));
}

#[test]
fn an_overlap_is_told_once_per_pair_until_one_lands_or_ends_and_names_functions() {
    let _g = SERIAL.lock().unwrap();
    scratch("overlap-once");
    let files = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
    let fns = |v: &[(&str, &[&str])]| -> crate::collab::Functions {
        v.iter().map(|(f, n)| (f.to_string(), n.iter().map(|s| s.to_string()).collect())).collect()
    };
    crate::collab::report_work_with("a", Some("feat/a"), &files(&["src/x.rs"]), Some(&fns(&[("src/x.rs", &["fn bar", "fn baz"])])), None).unwrap();
    // An old midas sends no functions: the note still names the file.
    crate::collab::report_work("b", Some("feat/b"), &files(&["src/x.rs"])).unwrap();
    assert_eq!(notes_for("a"), vec!["b (feat/b) also changes 1 file you change:\n  src/x.rs — you: fn bar, fn baz\nanswer them: midas say b \"…\""]);
    assert_eq!(notes_for("b"), vec!["a (feat/a) also changes 1 file you change:\n  src/x.rs — them: fn bar, fn baz\nanswer them: midas say a \"…\""]);
    // Their work parts and meets again: no news.
    crate::collab::report_work("b", Some("feat/b"), &files(&["src/y.rs"])).unwrap();
    crate::collab::report_work_with("b", Some("feat/b"), &files(&["src/x.rs"]), Some(&fns(&[("src/x.rs", &["fn qux"])])), None).unwrap();
    assert!(notes_for("a").is_empty() && notes_for("b").is_empty());
    // b's session ends and starts again at once: the same session carrying on.
    mark("session_end", "b", 0, json!({"reason": "other"}));
    assert!(collab_state()["work"]["b"].is_null(), "its work goes");
    crate::collab::report_work_with("b", Some("feat/b"), &files(&["src/x.rs"]), None, None).unwrap();
    assert!(notes_for("a").is_empty() && notes_for("b").is_empty(), "no news after a restart");
    // Ended for longer than a restart takes: the record goes, so a new b is told afresh.
    mark("session_end", "b", 0, json!({"reason": "other"}));
    let mut st = collab_state();
    st["ended"]["b"] = json!(registry::now() - 3600);
    set_collab_state(&st);
    crate::collab::report_work("c", None, &files(&["src/unrelated.rs"])).unwrap();
    assert!(collab_state()["told"].as_object().unwrap().is_empty());
    crate::collab::report_work_with("b", Some("feat/b2"), &files(&["src/x.rs"]), Some(&fns(&[("src/x.rs", &["fn qux"])])), None).unwrap();
    assert_eq!(notes_for("a"), vec!["b (feat/b2) also changes 1 file you change:\n  src/x.rs — you: fn bar, fn baz; them: fn qux\nanswer them: midas say b \"…\""]);
    // The page has it as data: the session, and each file's sides.
    let about = &collab_state()["notes"]["b"].as_array().unwrap().last().unwrap()["about"].clone();
    assert_eq!((about["with"].as_str(), about["files"][0]["file"].as_str()), (Some("a"), Some("src/x.rs")));
    assert_eq!(about["files"][0]["you"], json!(["fn qux"]));
    // A place both change is said.
    crate::collab::report_work_with("c", Some("feat/c"), &files(&["src/x.rs"]), Some(&fns(&[("src/x.rs", &["fn bar"])])), None).unwrap();
    assert!(notes_for("a").iter().any(|n| n.contains("— you: fn bar, fn baz; them: fn bar (both: fn bar)")), "{:?}", notes_for("a"));
    // Landing clears it too (b and c's pair is theirs).
    crate::collab::landed("a", None, None);
    assert!(!collab_state()["told"].as_object().unwrap().keys().any(|k| k.split('|').any(|o| o == "a")));
    assert!(collab_state()["work"]["a"].is_null());
}

#[test]
fn hunk_headers_name_the_functions_a_diff_changes() {
    let diff = "diff --git a/src/collab.rs b/src/collab.rs\n--- a/src/collab.rs\n+++ b/src/collab.rs\n\
                @@ -10,0 +11,2 @@ pub(crate) fn report_work(owner: &str) -> Result<()> {\n+x\n\
                @@ -40 +42 @@ impl Collab {\n-y\n+z\n@@ -50 +52 @@ impl Collab {\n-y\n+z\n\
                @@ -60 +62 @@\n-q\n\
                diff --git a/web/app.ts b/web/app.ts\n--- a/web/app.ts\n+++ b/web/app.ts\n\
                @@ -1 +1 @@ export async function load(id: string) {\n-a\n+b\n\
                diff --git a/gone.py b/gone.py\n--- a/gone.py\n+++ /dev/null\n@@ -1,3 +0,0 @@ def gone(x):\n-a\n";
    let f = crate::collab::hunk_functions(diff);
    assert_eq!(f["src/collab.rs"], vec!["report_work", "Collab"]);
    assert_eq!(f["web/app.ts"], vec!["load"]);
    assert_eq!(f["gone.py"], vec!["gone"], "a deleted file is named by its old path");
    // What names nothing goes; a heading is its words, a class its name.
    let noise = "--- a/m.tsx\n+++ b/m.tsx\n@@ -1 +1 @@ import {a} from 'b'\n\
                 @@ -9 +9 @@ class KeyDialog extends MithrilComponent<Attrs> {\n@@ -20 +20 @@ impl<T> Store<T> {\n\
                 --- a/d.md\n+++ b/d.md\n@@ -3 +3 @@ ### Home, Sessions\n";
    let f = crate::collab::hunk_functions(noise);
    assert_eq!(f["m.tsx"], vec!["KeyDialog", "Store"]);
    assert_eq!(f["d.md"], vec!["Home, Sessions"]);
    let many: String = (0..20).map(|i| format!("@@ -{i} +{i} @@ fn f{i}()\n")).collect();
    let f = crate::collab::hunk_functions(&format!("--- a/x.rs\n+++ b/x.rs\n{many}"));
    assert_eq!(f["x.rs"].len(), crate::collab::MAX_FUNCTIONS);
}

#[test]
fn a_hosted_session_is_named_by_its_id_and_answered_by_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("short-names");
    mark("session_start", "session-s5", 30, json!({"branch": "session/s5"}));
    mark("session_start", "b", 30, json!({"branch": "feat/b"}));
    let files = vec!["src/x.rs".to_string()];
    crate::collab::report_work("session-s5", Some("session/s5"), &files).unwrap();
    crate::collab::report_work("b", Some("feat/b"), &files).unwrap();
    assert_eq!(notes_for("b"), vec!["s5 also changes 1 file you change:\n  src/x.rs\nanswer them: midas say s5 \"…\""],
               "no session- before it, and no branch that only repeats it");
    assert_eq!(crate::collab::resolve("s5").unwrap(), "session-s5");
    let sent = crate::collab::say_to("session-s5", "b", "mine is the header", None).unwrap();
    let got = crate::collab::take_notes("b").unwrap();
    assert_eq!(crate::collab::note_line(&got[0]),
               format!("midas: note {} from s5: mine is the header — reply: midas say --re {} \"…\"", sent[0]["id"].as_str().unwrap(), sent[0]["id"].as_str().unwrap()));
}

#[test]
fn a_note_or_a_task_end_is_no_name_for_a_session() {
    assert!(crate::collab::not_a_name("From the build workspace — midas: session-s477 (\"Mode-regel\") is"));
    assert!(crate::collab::not_a_name("midas: b (feat/b) also changes 1 file you change:"));
    assert!(crate::collab::not_a_name(" <task-notification> <task-id>besrnp1yh</task-id>"));
    assert!(!crate::collab::not_a_name("Kun je kijken of de berichten van midas beter kunnen?"));
}

#[test]
fn an_edit_makes_an_overlap_news_at_once() {
    let _g = SERIAL.lock().unwrap();
    scratch("editing");
    crate::collab::report_work("one", Some("b1"), &["src/a.rs".into()]).unwrap();
    crate::collab::editing("two", Some("b2"), &["src/b.rs".into()]).unwrap();
    assert!(notes_for("one").is_empty() && notes_for("two").is_empty());
    crate::collab::editing("two", None, &["src/a.rs".into()]).unwrap();
    assert!(notes_for("one").iter().any(|n| n.contains("two (b2)") && n.contains("src/a.rs")), "both hear, and the branch is kept");
    assert!(notes_for("two").iter().any(|n| n.contains("src/a.rs")));
    crate::collab::editing("two", None, &["src/a.rs".into()]).unwrap();
    assert!(notes_for("one").is_empty(), "once per file in common");
}

#[test]
fn a_session_across_projects_keeps_each_ones_files_and_two_projects_same_path_is_no_overlap() {
    let _g = SERIAL.lock().unwrap();
    scratch("work-projects");
    let files = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
    let changed = |o: &str| collab_state()["work"][o]["files"].clone();
    crate::collab::report_work_with("s1", Some("session/s1"), &files(&["src/main.rs", "Cargo.lock"]), None, Some("acme/midas")).unwrap();
    crate::collab::report_work_with("s1", Some("session/s1"), &files(&["web/app.ts"]), None, Some("acme/podium")).unwrap();
    assert_eq!(changed("s1"), json!(["midas:src/main.rs", "podium:web/app.ts"]), "a build in one project keeps the other's");
    crate::collab::report_work_with("s1", Some("session/s1"), &files(&[]), None, Some("acme/midas")).unwrap();
    assert_eq!(changed("s1"), json!(["podium:web/app.ts"]), "and replaces its own");

    let found = crate::collab::report_work_with("s2", Some("session/s2"), &files(&["web/app.ts"]), None, Some("acme/cartopolis")).unwrap();
    assert!(found.is_empty() && notes_for("s1").is_empty(), "the same path in another project");
    crate::collab::editing_with("s2", None, &files(&["web/app.ts"]), None, Some("acme/podium")).unwrap();
    assert!(notes_for("s1").iter().any(|n| n.contains("podium:web/app.ts")), "the same file of the same project");
}

#[test]
fn a_session_folder_drops_the_files_of_projects_it_no_longer_spans() {
    let _g = SERIAL.lock().unwrap();
    scratch("work-folder-projects");
    let files = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
    let changed = |o: &str| collab_state()["work"][o]["files"].clone();
    // What a midas before folder_inside sent: the host checkout's loose files.
    crate::collab::report_work_with("s1", Some("session/s1"), &files(&["gk_ab.sh"]), None, Some("acme/cartopolis")).unwrap();
    crate::collab::report_work_with("s1", Some("session/s1"), &files(&["src/a.rs"]), None, Some("acme/podium")).unwrap();
    crate::collab::report_work_in("s1", Some("session/s1"), &files(&["src/main.rs"]), None, Some("acme/midas"),
                                  Some(&files(&["midas", "podium"]))).unwrap();
    assert_eq!(changed("s1"), json!(["midas:src/main.rs", "podium:src/a.rs"]), "a project the folder has stays, one it lacks goes");
    crate::collab::report_work_in("s1", Some("session/s1"), &files(&[]), None, None, Some(&[])).unwrap();
    assert_eq!(changed("s1"), json!([]), "a folder with no project changes nothing");
}

#[test]
fn a_decision_reaches_the_asker_and_those_it_names() {
    let _g = SERIAL.lock().unwrap();
    scratch("decide");
    assert!(crate::collab::decision_add("a", "q", &["only".into()], &[]).is_err(), "one option is no choice");
    let id = crate::collab::decision_add("a", "Who carries on the routing work?", &["a".into(), "b".into()], &["b".into()]).unwrap();
    assert!(crate::collab::decision_answer(&id, "c", "web", None).is_err());
    crate::collab::decision_answer(&id, "2", "workstation:web", Some("b knows it")).unwrap();
    for o in ["a", "b"] {
        assert_eq!(notes_for(o), vec![format!("The person decided {id} (\"Who carries on the routing work?\"): b — b knows it")]);
    }
    assert!(crate::collab::decision_answer(&id, "1", "web", None).is_err(), "decided once");
    let free = crate::collab::decision_add("a", "Name for the mode?", &[], &[]).unwrap();
    assert_eq!(crate::collab::decision_answer(&free, "street", "web", None).unwrap()["answer"], "street");
    assert_eq!(crate::collab::decisions().as_array().unwrap().len(), 2);
}

#[test]
fn the_collab_weeks_count_what_the_log_says() {
    let ev = |kind: &str, ts: &str, extra: Value| { let mut e = extra; e["kind"] = json!(kind); e["ts"] = json!(ts); e };
    let evs = vec![
        ev("session_start", "2026-10-19T08:00:00Z", json!({"actor": "s1"})),
        ev("session_start", "2026-10-19T09:00:00Z", json!({"actor": "gate-s1"})),
        ev("landing_done", "2026-10-19T10:00:00Z", json!({"actor": "s1", "outcome": "landed"})),
        ev("landing_done", "2026-10-20T10:00:00Z", json!({"actor": "s1", "outcome": "failed"})),
        ev("note", "2026-10-19T10:00:00Z", json!({"actor": "hub", "text": "x is also changing a.rs"})),
        ev("note", "2026-10-19T10:00:00Z", json!({"actor": "s1", "note_kind": "say", "text": "hi"})),
        ev("notes_taken", "2026-10-19T10:01:00Z", json!({"actor": "s2", "notes": [{"age_s": 60}, {"age_s": 120}, {"age_s": 30}]})),
        // Held 2 h, of which one 30-minute ssh session ran on the node: 1.5 h idle.
        ev("ssh_session", "2026-10-19T12:30:00Z", json!({"actor": "s1", "node": "n1", "phase": "close", "duration_s": 1800})),
        ev("release", "2026-10-19T13:00:00Z", json!({"actor": "s1", "holder": "s1", "node": "n1", "held_s": 7200})),
        ev("release", "2026-10-19T13:00:00Z", json!({"actor": "warmer", "holder": "warmer", "node": "n1", "held_s": 7200})),
        ev("claim", "2026-10-26T08:00:00Z", json!({"actor": "s3", "waited_s": 300})),
    ];
    let w = crate::stats::collab_weeks(&evs);
    assert_eq!(w.len(), 2);
    assert_eq!((w[0].week.as_str(), w[0].sessions, w[0].landed, w[0].failed), ("2026-W43", 1, 1, 1), "a gate is its session");
    assert_eq!(w[0].notes.get("overlap"), Some(&1), "read off the wording before note_kind was logged");
    assert_eq!(w[0].notes.get("say"), Some(&1));
    assert_eq!(w[0].note_wait_s, Some(60.0));
    assert!((w[0].idle_held_h - 1.5).abs() < 1e-9, "{}", w[0].idle_held_h);
    assert_eq!((w[1].week.as_str(), w[1].node_wait_s), ("2026-W44", Some(300.0)));
}

/// The code an authenticator with `secret` (base32) shows `steps` steps from now.
fn code_for(secret: &str, steps: i64) -> String {
    let key = data_encoding::BASE32_NOPAD.decode(secret.as_bytes()).unwrap();
    format!("{:06}", crate::accounts::hotp(&key, (registry::now() / 30 + steps) as u64, 6))
}

#[test]
fn an_account_is_set_up_with_a_password_and_a_code_and_logs_in_with_both() {
    use crate::accounts;
    let _g = SERIAL.lock().unwrap();
    scratch("accounts");
    assert!(accounts::add("Sam", "admin", "t").is_err(), "lowercase names");
    assert!(accounts::add("sam", "boss", "t").is_err(), "a known role");
    let tok = accounts::add("sam", "admin", "t").unwrap();
    assert!(accounts::add("sam", "viewer", "t").is_err(), "once");
    assert!(accounts::login("sam", "", "", "p").is_err(), "nothing to log in with before setup");

    let info = accounts::setup_info(&tok, "midas").unwrap();
    let secret = info["secret"].as_str().unwrap().to_string();
    assert!(info["uri"].as_str().unwrap().starts_with("otpauth://totp/midas%3Asam?secret="));
    assert!(info["qr_svg"].as_str().unwrap().contains("<svg"));
    assert!(accounts::setup_complete(&tok, "short", &code_for(&secret, 0)).is_err(), "twelve characters at least");
    assert!(accounts::setup_complete(&tok, "a long enough password", "000000").is_err() || code_for(&secret, 0) == "000000");
    let recovery = accounts::setup_complete(&tok, "a long enough password", &code_for(&secret, 0)).unwrap();
    assert_eq!(recovery.len(), 10);
    assert!(accounts::setup_info(&tok, "midas").is_err(), "a setup link works once");

    // The code used at setup is spent; the next one logs in, and only once.
    assert!(accounts::login("sam", "a long enough password", &code_for(&secret, 0), "p").is_err());
    // One code, read once: computed again, it is the next step's after a 30 s boundary.
    let next = code_for(&secret, 1);
    let (session, role) = accounts::login("sam", "a long enough password", &next, "p").unwrap();
    assert_eq!(role, "admin");
    assert_eq!(accounts::session(&session), Some(("sam".into(), "admin".into())));
    assert!(accounts::login("sam", "a long enough password", &next, "p").is_err(), "no replay");
    assert!(accounts::login("sam", "wrong password here", &recovery[0], "p").is_err(), "a recovery code needs the password");
    accounts::login("sam", "a long enough password", &recovery[0].to_uppercase(), "p").unwrap();
    assert!(accounts::login("sam", "a long enough password", &recovery[0], "p").is_err(), "a recovery code once");
    assert!(accounts::login("nobody", "a long enough password", "123456", "p").is_err());

    accounts::set_role("sam", "viewer", "t").unwrap();
    assert_eq!(accounts::session(&session).unwrap().1, "viewer", "a live session takes the new role");
    accounts::logout(&session);
    assert_eq!(accounts::session(&session), None);
}

#[test]
fn five_failed_logins_lock_an_account_and_a_reset_starts_it_over() {
    use crate::accounts;
    let _g = SERIAL.lock().unwrap();
    scratch("lockout");
    let tok = accounts::add("ana", "operator", "t").unwrap();
    let secret = accounts::setup_info(&tok, "midas").unwrap()["secret"].as_str().unwrap().to_string();
    accounts::setup_complete(&tok, "correct horse battery", &code_for(&secret, 0)).unwrap();
    let (session, _) = accounts::login("ana", "correct horse battery", &code_for(&secret, 1), "p").unwrap();
    for _ in 0..5 {
        assert!(accounts::login("ana", "guess guess guess", "123456", "p").is_err());
    }
    let e = accounts::login("ana", "correct horse battery", &code_for(&secret, 0), "p").unwrap_err().to_string();
    assert!(e.contains("too many failed logins"), "{e}");
    assert_eq!(accounts::list().unwrap()[0]["locked"], true);

    let tok = accounts::reset("ana", "t").unwrap();
    assert_eq!(accounts::session(&session), None, "a reset logs out");
    assert!(accounts::login("ana", "correct horse battery", &code_for(&secret, 1), "p").is_err(), "the old password is gone");
    let secret2 = accounts::setup_info(&tok, "midas").unwrap()["secret"].as_str().unwrap().to_string();
    assert_ne!(secret, secret2, "and a new code secret");
    accounts::remove("ana", "t").unwrap();
    assert!(accounts::list().unwrap().as_array().unwrap().is_empty());
}

#[test]
fn a_bare_agent_is_midas_own_and_a_named_one_is_kept() {
    use clap::Parser;
    let agent = |args: &[&str]| match crate::Cli::try_parse_from(args).unwrap().cmd {
        crate::Cmd::Bot(crate::BotCmd::Start { agent, .. }) => agent,
        _ => panic!("not bot start"),
    };
    assert_eq!(agent(&["midas", "bot", "start", "--mcp", "r", "--agent", "--name", "v", "--", "x"]), Some(None));
    assert_eq!(agent(&["midas", "bot", "start", "--mcp", "r", "--agent=other-acp", "--", "x"]), Some(Some("other-acp".into())));
    // A bare --agent leaves the machine alone.
    let cli = crate::Cli::try_parse_from(["midas", "bot", "start", "--mcp", "r", "--agent", "gpu", "--", "x"]).unwrap();
    assert!(matches!(cli.cmd, crate::Cmd::Bot(crate::BotCmd::Start { agent: Some(None), ref machine, .. }) if machine == "gpu"));
    assert_eq!(agent(&["midas", "bot", "start", "--mcp", "r", "--", "x"]), None);
}

#[test]
fn a_session_starts_in_the_mode_asked_and_keeps_what_it_shows() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("hosted");
    let id = sessions::start("ana", "draw a cat", None, None, Some("bypassPermissions"), Some("opus"), None, &Value::Null).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["mode"], "bypassPermissions");
    assert!(sessions::start("ana", "x", None, None, Some("../etc"), None, None, &Value::Null).is_err(), "a mode is a name, not a path");
    assert_eq!(sessions::meta(&sessions::start("ana", "z", None, None, None, None, None, &Value::Null).unwrap()).unwrap()["mode"], "bypassPermissions",
               "Trusted when none is chosen");
    assert!(sessions::start("ana", "x", None, None, None, Some("opus; rm -rf /"), None, &Value::Null).is_err(), "a model is a name");
    assert_eq!(sessions::meta(&sessions::start("ana", "y", None, None, None, Some("default"), None, &Value::Null).unwrap()).unwrap()["model"], serde_json::Value::Null,
               "default is no model asked for");
    assert_eq!(sessions::meta(&sessions::start("ana", "w", None, None, None, None, Some("claude"), &Value::Null).unwrap()).unwrap()["agent"], serde_json::Value::Null,
               "Claude Code is no agent asked for, as before there was a choice");
    assert!(sessions::start("ana", "v", None, None, None, None, Some("codex"), &Value::Null).is_err(), "only an agent the hub has");
    assert!(crate::agents::set("claude", "Mine", "x", "ana").is_err(), "Claude Code is built in");
    assert!(crate::agents::set("Co dex", "Codex", "codex-acp", "ana").is_err(), "an id is a name");
    assert!(crate::agents::set("codex", "Codex", "codex-acp\nrm -rf /", "ana").is_err(), "a command is one line");
    crate::agents::set("codex", "Codex", "OPENAI_API_KEY=sk-x codex-acp", "ana").unwrap();
    let started = sessions::start("ana", "u", None, None, None, None, Some("codex"), &Value::Null).unwrap();
    assert_eq!(sessions::meta(&started).unwrap()["agent"], "codex", "kept, so reopening starts it again");
    let offered = crate::agents::list(false);
    assert_eq!((offered[0]["id"].as_str(), offered[1]["name"].as_str()), (Some("claude"), Some("Codex")), "Claude Code first");
    assert!(offered[1].get("command").is_none(), "the page's list carries no command: it may hold a key");
    assert_eq!(crate::agents::command("codex").unwrap(), "OPENAI_API_KEY=sk-x codex-acp");
    assert!(crate::agents::remove("codex", "ana").unwrap());
    assert!(crate::agents::command("codex").is_err(), "gone, a session of it fails to start rather than run another");
    sessions::tell(&id, "mode", &json!({"mode": "plan"}), "ana").unwrap();
    assert!(sessions::tell(&id, "mode", &json!({"mode": ""}), "ana").is_err());

    let file = sessions::add_media(&id, "../cat render.png", Some("the cat"), b"PNG").unwrap();
    assert_eq!(file, "1-_cat_render.png", "no dots in front, nothing that walks");
    let p = sessions::media_path(&id, &file).expect("kept");
    assert_eq!(std::fs::read(p).unwrap(), b"PNG");
    assert!(sessions::media_path(&id, "../meta.json").is_none(), "nothing outside its media");
    let log = sessions::log(&id, 0).unwrap();
    let item = log["items"].as_array().unwrap().last().unwrap().clone();
    assert_eq!((item["kind"].as_str(), item["mime"].as_str(), item["caption"].as_str()), (Some("media"), Some("image/png"), Some("the cat")));

    // Ended, it can be reopened: its agent's conversation kept, its inbox read from here on.
    sessions::push(&id, &[json!({"kind": "mode", "current": "plan"})], Some("stopped"), "runner@x", Some("conv-1"), None).unwrap();
    // What waits for the agent is the runner's to say, and the page's to edit through it.
    let q = json!([{"qid": 7, "text": "then the tests", "by": "ana"}]);
    sessions::push(&id, &[], None, "runner@x", None, Some(&q)).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["queue"], q);
    // Edits to it go to a live session (an ended one hears nothing), checked first.
    let live = sessions::start("ana", "a live one", None, None, None, None, None, &Value::Null).unwrap();
    sessions::tell(&live, "queue", &json!({"op": "edit", "qid": 7, "text": "then all the tests"}), "ana").unwrap();
    sessions::tell(&live, "queue", &json!({"op": "clear"}), "ana").unwrap();
    assert!(sessions::tell(&live, "queue", &json!({"op": "shuffle", "qid": 7}), "ana").is_err(), "a known op");
    assert!(sessions::tell(&live, "queue", &json!({"op": "edit", "qid": 7, "text": " "}), "ana").is_err(), "an edit says something");
    assert!(sessions::tell(&live, "queue", &json!({"op": "move", "qid": 7}), "ana").is_err(), "a move says where");
    assert!(sessions::tell(&live, "queue", &json!({"op": "remove"}), "ana").is_err(), "and which message");
    assert_eq!(sessions::meta(&id).unwrap()["agent_session"], "conv-1");
    sessions::reopen(&id, "ana", "").unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["reopen"].as_bool(), m["inbox_after"].as_u64()), (Some("queued"), Some(true), Some(2)));
    assert_eq!(m["mode"], "plan", "back in the mode it was last in");
    assert!(sessions::reopen(&id, "ana", "").is_err(), "not twice while it starts");
}

#[test]
fn a_runner_that_died_mid_start_starts_its_session_again() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("taken-back");
    let id = sessions::start("ana", "fix the layout", None, None, None, None, None, &Value::Null).unwrap();
    let got = sessions::poll("runner@x", &json!({}), true).unwrap();
    assert_eq!(got["start"][0]["id"], id.as_str());
    assert_eq!(sessions::meta(&id).unwrap()["status"], "starting");
    assert!(sessions::reopen(&id, "ana", "").is_err(), "a person may not, while it starts");
    assert!(sessions::take_back(&id, "runner@y", "runner").is_err(), "another runner's");
    sessions::take_back(&id, "runner@x", "runner").unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["reopen"].as_bool()), (Some("queued"), None), "a fresh start, as it was");

    // Taken back in the middle of a turn: reloaded, and told the turn was cut off.
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[], Some("working"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::take_back(&id, "runner@x", "runner").unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["reopen"].as_bool(), m["cut_off"].as_bool()), (Some("queued"), Some(true), Some(true)));
    // Idle when it went: nothing was cut off.
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[], Some("waiting"), "runner@x", None, None).unwrap();
    sessions::take_back(&id, "runner@x", "runner").unwrap();
    assert!(sessions::meta(&id).unwrap()["cut_off"].is_null(), "an idle session is only reloaded");
}

#[test]
fn a_start_taken_by_a_poll_its_runner_left_is_given_again() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("lost-start");
    let id = sessions::start("ana", "fix the layout", None, None, None, None, None, &Value::Null).unwrap();
    // The poll of a runner that was stopped takes it; its answer goes nowhere.
    assert_eq!(sessions::poll("runner@x", &json!({}), true).unwrap()["start"][0]["id"], id.as_str());
    let meta = registry::root().join("hosted").join(&id).join("meta.json");
    let age = |secs: i64| {
        let mut m = sessions::meta(&id).unwrap();
        m["updated"] = json!(registry::now() - secs);
        std::fs::write(&meta, m.to_string()).unwrap();
    };
    // Its runner, started again, does not have it: given again once a poll's time has passed.
    age(60);
    let got = sessions::poll("runner@x", &json!({}), true).unwrap();
    assert_eq!(got["start"][0]["id"], id.as_str());
    // Not again while that start is under way, nor to a runner that has it, nor to another.
    age(60);
    assert!(sessions::poll("runner@x", &json!({id.as_str(): 0}), true).unwrap()["start"].as_array().unwrap().is_empty());
    assert!(sessions::poll("runner@y", &json!({}), true).unwrap()["start"].as_array().unwrap().is_empty());
}

#[test]
fn a_session_is_renamed_when_its_subject_changes() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("renamed");
    let id = sessions::start("ana", "## Goal\nfix the layout", None, None, None, None, None, &Value::Null).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["title"], "fix the layout");
    assert_eq!(sessions::set_title(&id, "Voice agent for calls\nmore", "session-x").unwrap(), "Voice agent for calls");
    assert_eq!(sessions::meta(&id).unwrap()["title"], "Voice agent for calls");
    assert!(sessions::set_title(&id, "  ", "session-x").is_err(), "a name, not nothing");
}

#[test]
fn an_editors_session_is_mirrored_steered_and_never_taken_over() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("attached");
    let conv = "11111111-2222-4333-8444-555555555555";
    let local = json!({"client": "Zed", "machine": "mini", "cwd": "/Users/x/code/cartopolis"});
    assert!(sessions::attach("mini", "zed@mini", "../meta", "x", &local, None, "cartopolis").is_err(), "an agent's id, not a path");
    let a = sessions::attach("mini", "zed@mini", conv, "Fix the sky\nand more", &local, Some("main"), "cartopolis").unwrap();
    let id = a["id"].as_str().unwrap().to_string();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["title"].as_str(), m["local"]["client"].as_str(), m["branch"].as_str()),
               (Some("waiting"), Some("Fix the sky"), Some("Zed"), Some("main")));
    // The page steers it; the mirror hears it, and a runner's poll does not take it.
    sessions::tell(&id, "message", &json!({"text": "and the stars"}), "web:ana").unwrap();
    let queued = sessions::start("ana", "a runner's", None, None, None, None, None, &Value::Null).unwrap();
    let heard = sessions::poll("zed@mini", &json!({id.as_str(): 0}), false).unwrap();
    assert_eq!(heard["inputs"][&id][0]["text"], "and the stars");
    assert!(heard["start"].as_array().unwrap().is_empty(), "a mirror starts nothing");
    assert_eq!(sessions::meta(&queued).unwrap()["status"], "queued", "left for a runner");
    // On the board, under its checkout's name and its first prompt, while it is open.
    let on_board = || crate::builds::sessions(3600).into_iter().find(|s| s["actor"] == "cartopolis");
    let card = on_board().expect("a session on the board");
    assert_eq!((card["open"].as_bool(), card["label"].as_str()), (Some(true), Some("Fix the sky")));
    // Ended in the editor, it is not reopened here: its conversation is there.
    sessions::push(&id, &[], Some("stopped"), "zed@mini", None, None).unwrap();
    assert!(sessions::reopen(&id, "ana", "").is_err());
    assert_eq!(on_board().unwrap()["open"], false, "off the board once it ends");
    // Loaded in the editor again: the same session, its inbox heard from here on.
    // (A second on: the history counts in whole seconds, and an end and a start in one are ended.)
    std::thread::sleep(std::time::Duration::from_millis(1100));
    let again = sessions::attach("mini", "zed@mini", conv, "", &local, Some("main"), "cartopolis").unwrap();
    assert_eq!((again["id"].as_str(), again["inbox_after"].as_u64()), (Some(id.as_str()), Some(1)));
    assert_eq!(sessions::meta(&id).unwrap()["title"], "Fix the sky", "its title kept");
    assert_eq!(on_board().unwrap()["open"], true, "and back on the board");
}

#[test]
fn an_editors_session_its_mirror_stops_asking_after_reads_as_closed_there() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("mirror-gone");
    let conv = "33333333-2222-4333-8444-555555555555";
    let local = json!({"client": "Zed", "machine": "mini", "cwd": "/Users/x/code/podium"});
    let id = sessions::attach("mini", "zed@mini", conv, "Fix the sky", &local, Some("main"), "podium").unwrap()["id"].as_str().unwrap().to_string();
    // A hub that has listened for less than the grace has heard nobody yet: nothing ends.
    sessions::sweep_mirrors_after(std::time::Duration::from_secs(3600));
    assert_eq!(sessions::meta(&id).unwrap()["status"], "waiting");
    // Its mirror went without a word: ended on the page, with why.
    sessions::sweep_mirrors_after(std::time::Duration::ZERO);
    let m = sessions::meta(&id).unwrap();
    assert_eq!(m["status"], "stopped");
    assert!(m["gone"].as_i64().is_some());
    let log = std::fs::read_to_string(crate::registry::root().join("hosted").join(&id).join("log.jsonl")).unwrap();
    assert!(log.contains("no longer has it open"), "{log}");
    // Another runner naming it does not bring it back; its own mirror does.
    sessions::poll("runner@x", &json!({id.as_str(): 0}), false).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["status"], "stopped");
    sessions::poll("zed@mini", &json!({id.as_str(): 0}), false).unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["gone"].is_null()), (Some("waiting"), true));
    // One that ended in the editor is not the sweep's: it stays as it ended.
    sessions::push(&id, &[], Some("stopped"), "zed@mini", None, None).unwrap();
    sessions::sweep_mirrors_after(std::time::Duration::ZERO);
    assert!(sessions::meta(&id).unwrap()["gone"].is_null());
}

#[test]
fn an_editors_session_goes_to_the_runner_and_back_and_each_side_hears_only_its_own_turn() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("handoff");
    let conv = "22222222-2222-4333-8444-555555555555";
    let local = json!({"client": "Zed", "machine": "mini", "cwd": "/Users/x/code/cartopolis"});
    let id = sessions::attach("mini", "zed@mini", conv, "Fix the sky", &local, Some("main"), "cartopolis").unwrap()["id"].as_str().unwrap().to_string();
    sessions::push(&id, &[json!({"kind": "mode", "current": "bypassPermissions"}), json!({"kind": "model", "current": "haiku"})],
                   None, "zed@mini", None, None).unwrap();
    assert!(sessions::tell(&id, "handback", &json!({}), "web:ana").is_err(), "not at the hub yet");
    sessions::tell(&id, "handoff", &json!({}), "web:ana").unwrap();
    assert!(sessions::handed(&id, "abc", true).is_err(), "not without its transcript");
    sessions::put_transcript(&id, b"{}\n").unwrap();
    sessions::handed(&id, "abc", true).unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["branch"].as_str(), m["base"].as_str(), m["owner"].as_str()),
               (Some("queued"), Some(format!("session/{id}").as_str()), Some(format!("session/{id}").as_str()), Some(format!("session-{id}").as_str())));
    assert!(m["local"].is_null() && m["handed"]["from"]["machine"] == "mini" && m["handed"]["by"] == "web:ana");
    assert_eq!((m["mode"].as_str(), m["model"].as_str()), (Some("bypassPermissions"), Some("haiku")), "in the mode and on the model it had");
    assert_eq!(m["reopen"], true, "the runner loads its conversation");
    // The editor's side says something late: not heard; the runner takes it.
    sessions::push(&id, &[], Some("waiting"), "zed@mini", None, None).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["status"], "queued");
    let got = sessions::poll("runner@x", &json!({}), true).unwrap();
    assert_eq!(got["start"][0]["id"], id.as_str());
    sessions::push(&id, &[], Some("waiting"), "runner@x", None, None).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["status"], "waiting");
    assert!(sessions::tell(&id, "handoff", &json!({}), "web:ana").is_err(), "here already");

    // Back: the editor's again, ended here, waiting for the editor to take it.
    sessions::tell(&id, "handback", &json!({}), "web:ana").unwrap();
    sessions::put_transcript(&id, b"{}\n{}\n").unwrap();
    sessions::handed_back(&id, "def").unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["local"]["machine"].as_str(), m["owner"].as_str(), m["branch"].as_str()),
               (Some("stopped"), Some("mini"), Some("cartopolis"), Some("main")));
    assert_eq!((m["back"]["pending"].as_bool(), m["back"]["sha"].as_str()), (Some(true), Some("def")));
    sessions::push(&id, &[], Some("failed"), "runner@x", None, None).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["status"], "stopped", "the runner's late word is not heard");
    assert!(sessions::reopen(&id, "ana", "").is_err(), "the editor's to open");
    // Opened in the editor again: the same session, taken.
    let again = sessions::attach("mini", "zed@mini", conv, "", &local, Some("main"), "cartopolis").unwrap();
    assert_eq!(again["id"], id.as_str());
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["back"]["pending"].as_bool()), (Some("waiting"), Some(false)));
}

#[test]
fn a_pasted_image_goes_with_its_message_once() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("pasted");
    assert!(sessions::upload("notes.txt", b"hi").is_err(), "an image only");
    let png = b"\x89PNG fake";
    let t = sessions::upload("Screen Shot 1.png", png).unwrap();
    assert!(t.starts_with("u-") && t.ends_with("-Screen_Shot_1.png"), "{t}");
    let id = sessions::start("ana", "", None, None, None, None, None, &json!([t.clone()])).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["title"], "A picture", "an image alone is a message");
    let inbox = std::fs::read_to_string(registry::root().join("hosted").join(&id).join("inbox.jsonl")).unwrap();
    let first: Value = serde_json::from_str(inbox.lines().next().unwrap()).unwrap();
    let img = &first["images"][0];
    assert_eq!((img["mime"].as_str(), img["data"].as_str()), (Some("image/png"), Some(data_encoding::BASE64.encode(png).as_str())));
    assert!(sessions::media_path(&id, img["file"].as_str().unwrap()).is_some(), "kept with the session, for the page");
    assert!(sessions::tell(&id, "message", &json!({"text": "again", "images": [t]}), "ana").is_err(), "sent once");
    let many: Vec<String> = (0..6).map(|i| sessions::upload(&format!("{i}.png"), png).unwrap()).collect();
    assert!(sessions::tell(&id, "message", &json!({"text": "all", "images": many}), "ana").is_err(), "five at most");
}

#[test]
fn status_says_when_a_lease_goes_back_by_the_rule_that_ends_it() {
    let t = registry::now();
    let build = json!({"owner": "wt", "renewed_at": t - 240, "claimed_at": t - 3600, "ttl": 7200});
    let idle = json!({"sessions": 0});
    assert_eq!(crate::cli::lease_end(&build, Some(&idle)), "given back after 30 min with no ssh session (last 4m ago)");
    assert_eq!(crate::cli::lease_end(&build, Some(&json!({"sessions": 2}))), "in use: 2 ssh sessions open");
    let bot = json!({"owner": "wt", "mode": "bot", "renewed_at": t, "contact_at": t - 600, "ttl": 7200});
    assert_eq!(crate::cli::lease_end(&bot, Some(&json!({"sessions": 0, "bot": {"running": true}}))),
               "bot running; given back after 30 min without word from its holder (last 10m ago)");
    assert!(crate::cli::lease_end(&build, None).starts_with("given back at "), "a node that does not report sessions: the TTL");
}

#[test]
fn an_imported_conversation_is_read_and_searched_but_not_reopened() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("imported");
    let f = json!({"key": "abc-123", "from": "mini", "title": "Fix the sea", "prompt": "Fix the sea", "branch": "fix/sea",
                   "owner": "bridge-x", "created": 1000, "updated": 2000});
    let id = sessions::import_begin("key-1", &f).unwrap()["id"].as_str().unwrap().to_string();
    sessions::import_items(&id, &[json!({"kind": "user", "text": "Fix the sea", "at": 1000}),
                                  json!({"kind": "agent", "text": "The diamonds are", "at": 1500})], false).unwrap();
    sessions::import_items(&id, &[json!({"kind": "agent", "text": " a depth fight.", "at": 1500}),
                                  json!({"kind": "tool", "id": "t", "title": "Bash: cargo test", "input": {"description": "Run the GLOBE tests"}}),
                                  json!({"kind": "permission", "request": "1"})], true).unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["status"].as_str(), m["imported"]["complete"].as_bool(), m["created"].as_i64()), (Some("stopped"), Some(true), Some(1000)));
    let items = sessions::log(&id, 0).unwrap()["items"].as_array().unwrap().clone();
    assert_eq!(items.len(), 4, "only what an import may bring");
    assert_eq!((items[1]["n"].as_u64(), items[1]["at"].as_i64()), (Some(2), Some(1500)), "numbered here, its time kept");
    assert!(sessions::reopen(&id, "ana", "").is_err(), "its agent's conversation is elsewhere");

    // Again, unchanged: nothing to send. Grown: its log again, under the same id.
    assert_eq!(sessions::import_begin("key-1", &f).unwrap()["have"], "imported");
    let grown = json!({"key": "abc-123", "from": "mini", "title": "Fix the sea", "created": 1000, "updated": 3000});
    let again = sessions::import_begin("key-1", &grown).unwrap();
    assert_eq!((again["id"].as_str(), again["have"].as_str()), (Some(id.as_str()), None));
    assert!(sessions::log(&id, 0).unwrap()["items"].as_array().unwrap().is_empty());
    sessions::import_items(&id, &[json!({"kind": "user", "text": "Fix the sea", "at": 1000}),
                                  json!({"kind": "agent", "text": "The diamonds are", "at": 1500}),
                                  json!({"kind": "agent", "text": " a depth fight.", "at": 1500}),
                                  json!({"kind": "tool", "id": "t", "title": "Bash: cargo test", "input": {"description": "Run the GLOBE tests"}})], true).unwrap();
    // Its project, given once it is known, and its tally with it.
    assert_eq!(sessions::import_begin("key-1", &json!({"key": "abc-123", "updated": 1000, "repo": "acme/cartopolis"})).unwrap()["have"], "imported");
    assert_eq!(sessions::meta(&id).unwrap()["repo"], "acme/cartopolis");
    let st = sessions::stats(i64::MAX / 2);
    let mine = st.as_array().unwrap().iter().find(|t| t["id"] == id.as_str()).unwrap();
    assert_eq!((mine["repo"].as_str(), mine["imported"].as_str(), mine["tool_calls"].as_u64()), (Some("acme/cartopolis"), Some("mini"), Some(1)));
    // A session midas ran is not imported again from its own transcript.
    let ran = sessions::start("ana", "draw a cat", None, None, None, None, None, &Value::Null).unwrap();
    sessions::push(&ran, &[json!({"kind": "agent", "text": "a depth cat"})], Some("stopped"), "runner@x", Some("conv-9"), None).unwrap();
    assert_eq!(sessions::import_begin("key-1", &json!({"key": "conv-9"})).unwrap()["id"], ran);

    // Every word, any case, across chunks the agent's text came in.
    let r = sessions::search("DEPTH fight", 50);
    let hits = r["results"].as_array().unwrap();
    assert_eq!(hits.len(), 1, "{r}");
    assert_eq!((hits[0]["id"].as_str(), hits[0]["n"].as_u64()), (Some(id.as_str()), Some(2)));
    assert_eq!(hits[0]["snippet"], "The diamonds are a depth fight.");
    assert_eq!(sessions::search("depth", 50)["results"].as_array().unwrap().len(), 2, "both say it");
    assert_eq!(sessions::search("globe tests", 50)["results"][0]["n"], 4, "a tool's purpose is searched");
    assert_eq!(sessions::search("depth", 1)["more"], true);
    assert!(sessions::search("x", 50)["results"].as_array().unwrap().is_empty(), "two characters at least");
    // The index follows a log that grows.
    sessions::push(&ran, &[json!({"kind": "agent", "text": "and a quokka"})], None, "runner@x", None, None).unwrap();
    assert_eq!(sessions::search("quokka", 50)["results"][0]["id"], ran);
}

#[test]
fn warm_and_deploy_steps_run_in_the_checkout_whatever_was_sent_last() {
    assert_eq!(crate::warm::in_checkout("git fetch --quiet origin"), "cd /work/checkout && git fetch --quiet origin");
}

#[test]
fn a_runner_starting_again_is_not_the_session_doing_something() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("revive");
    let id = sessions::start("ana", "fix the layout", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[], Some("working"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::push(&id, &[], Some("waiting"), "runner@x", None, None).unwrap();
    // Its last turn ended two days ago, and nothing has changed since its files report.
    sessions::put_files(&id, &json!({"files": [{"path": "src/x.rs", "status": "M", "add": 1, "del": 0}], "commits": 1, "clean": false})).unwrap();
    sessions::backdate(&id, 2 * 86400);
    let before = sessions::meta(&id).unwrap();
    // The runner restarts (a deploy): it takes the session back and loads it again.
    sessions::take_back(&id, "runner@x", "runner@x").unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[json!({"kind": "status", "text": "back, with its conversation"})], Some("waiting"), "runner@x", None, None).unwrap();
    let m = sessions::meta(&id).unwrap();
    assert_eq!(m["active"], before["active"], "still idle for two days");
    assert!(m["updated"].as_i64() > before["updated"].as_i64(), "its status moved, which the stuck-start warning reads");
    // A turn is the session doing something.
    sessions::push(&id, &[], Some("working"), "runner@x", None, None).unwrap();
    assert!(sessions::meta(&id).unwrap()["active"].as_i64() > before["active"].as_i64());
    // A person reopening it is too.
    sessions::push(&id, &[], Some("stopped"), "runner@x", None, None).unwrap();
    sessions::backdate(&id, 2 * 86400);
    let stopped = sessions::meta(&id).unwrap()["active"].clone();
    sessions::reopen(&id, "ana", "").unwrap();
    assert!(sessions::meta(&id).unwrap()["active"].as_i64() > stopped.as_i64());
}

#[test]
fn a_session_finishes_on_the_persons_answer_between_turns_and_keeps_what_it_landed() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("finish");
    let sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    let id = sessions::start("ana", "fix the layout", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[], Some("working"), "runner@x", Some("conv-1"), None).unwrap();
    // What its branch changes; a later report from a branch already on main keeps it.
    sessions::put_files(&id, &json!({"files": [{"path": "src/hub.rs", "status": "M", "add": 3, "del": 1}], "commits": 1})).unwrap();
    sessions::put_files(&id, &json!({"files": [], "commits": 0, "clean": true})).unwrap();
    assert_eq!(sessions::files(&id).unwrap()["files"][0]["path"], "src/hub.rs");

    assert!(sessions::finish(&id, "s", Some("abc"), None, false).is_err(), "a landed commit's full sha");
    sessions::finish(&id, "session-x", Some(sha), None, false).unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["finish"]["sha"], sha);
    // Mid-turn, the agent that landed it is not cut off.
    sessions::finish_sweep();
    assert!(sessions::meta(&id).unwrap()["finished"].is_null());
    // Between turns, in a workspace that deploys nothing after landings: finished at once.
    sessions::push(&id, &[], Some("waiting"), "runner@x", None, None).unwrap();
    sessions::finish_sweep();
    let m = sessions::meta(&id).unwrap();
    assert_eq!((m["finished"]["outcome"].as_str(), m["archived"].as_bool(), m["finish"].is_null()), (Some("landed"), Some(true), true));
    let log = sessions::log(&id, 0).unwrap();
    assert!(log["items"].as_array().unwrap().iter().any(|i| i["kind"] == "finished"), "said in its conversation");
    assert_eq!(sessions::inbox(&id).last().unwrap()["kind"], "stop", "its agent is ended");

    // Nothing to land: finished by itself once idle a while, and back under Running when reopened.
    let asked = sessions::start("ana", "what is this api for?", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&asked, &[], Some("waiting"), "runner@x", Some("conv-2"), None).unwrap();
    sessions::put_files(&asked, &json!({"files": [{"path": "notes.md", "status": "A", "add": 3, "del": 0}], "commits": 0, "clean": false})).unwrap();
    sessions::backdate(&asked, 3600);
    sessions::finish_sweep();
    assert!(sessions::meta(&asked).unwrap()["finished"].is_null(), "a file changed: it has work to land");
    sessions::put_files(&asked, &json!({"files": [], "commits": 0, "clean": true})).unwrap();
    sessions::backdate(&asked, 60);
    sessions::finish_sweep();
    assert!(sessions::meta(&asked).unwrap()["finished"].is_null(), "just answered: the person may follow up");
    sessions::backdate(&asked, 3600);
    sessions::finish_sweep();
    let m = sessions::meta(&asked).unwrap();
    assert_eq!((m["finished"]["outcome"].as_str(), m["archived"].as_bool()), (Some("done"), Some(true)));
    sessions::push(&asked, &[], Some("stopped"), "runner@x", None, None).unwrap();
    sessions::reopen(&asked, "ana", "").unwrap();
    let m = sessions::meta(&asked).unwrap();
    assert_eq!((m["finished"].is_null(), m["archived"].as_bool()), (true, Some(false)));

    // Marked done by the person, whatever its branch holds; not twice.
    sessions::put_files(&asked, &json!({"files": [{"path": "notes.md", "status": "A", "add": 3, "del": 0}], "commits": 1, "clean": false})).unwrap();
    sessions::mark_done(&asked, "ana").unwrap();
    assert_eq!(sessions::meta(&asked).unwrap()["finished"]["outcome"], "done");
    assert!(sessions::mark_done(&asked, "ana").is_err());

    // Landed in two projects: each said, one landing per project, a project landed again replacing its own.
    let both = sessions::start("ana", "a feature across two projects", Some("auto"), None, None, None, None, &Value::Null).unwrap();
    let m = sessions::meta(&both).unwrap();
    assert_eq!((m["layout"].as_str(), m["repo"].is_null(), sessions::repos_of(&m).len()), (Some("folder"), true, 0), "the agent adds its projects");
    let other_sha = "b1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    sessions::finish(&both, "session-x", Some(sha), Some("acme/midas"), false).unwrap();
    sessions::finish(&both, "session-x", Some(other_sha), Some("acme/podium.git"), false).unwrap();
    sessions::finish(&both, "session-x", Some(other_sha), Some("acme/podium"), false).unwrap();
    let landed = sessions::meta(&both).unwrap()["finish"]["landed"].clone();
    assert_eq!(landed, json!([{"sha": sha, "repo": "acme/midas"}, {"sha": other_sha, "repo": "acme/podium"}]));

    // Dropped: at once, nothing landed.
    let other = sessions::start("ana", "try something", None, None, None, None, None, &Value::Null).unwrap();
    sessions::finish(&other, "session-y", None, None, true).unwrap();
    assert_eq!(sessions::meta(&other).unwrap()["finished"]["outcome"], "dropped");
    assert_eq!(sessions::id_of_owner("session-s12").as_deref(), Some("s12"));
    assert_eq!(sessions::id_of_owner("bridge-cse_x"), None);
}

#[test]
fn a_session_set_to_carry_on_later_is_woken_then_and_left_alone_until() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("wake");
    let t = registry::now();
    assert_eq!(sessions::when_of(None, Some("1d12h"), t).unwrap(), t + 36 * 3600);
    assert_eq!(sessions::when_of(None, Some("90m"), t).unwrap(), t + 5400);
    assert!(sessions::when_of(None, Some("12"), t).is_err(), "a while has its unit");
    assert!(sessions::when_of(None, Some("2s"), t).is_err(), "minutes, hours or days");
    assert_eq!(sessions::when_of(Some("2026-10-30T09:00+01:00"), None, t).unwrap(), 1_793_347_200);
    assert_eq!(sessions::when_of(Some("2026-10-30 09:00:00+01:00"), None, t).unwrap(), 1_793_347_200);
    assert!(sessions::when_of(Some("2026-10-30 09:00"), None, t).is_err(), "a clock time says its offset");
    assert!(sessions::when_of(Some("1793347200"), Some("4h"), t).is_err(), "one or the other");

    // A question answered, nothing to land: it would finish once idle a while, but it is to carry on tomorrow.
    let id = sessions::start("ana", "summarise the motions", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[], Some("waiting"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::put_files(&id, &json!({"files": [], "commits": 0, "clean": true})).unwrap();
    assert!(sessions::set_wake(&id, t - 5, "the rest", "session-x").is_err(), "a time to come");
    assert!(sessions::set_wake(&id, t + 31 * 86400, "the rest", "session-x").is_err(), "within a month");
    assert!(sessions::set_wake(&id, t + 3600, " ", "session-x").is_err(), "says what to do then");
    sessions::set_wake(&id, t + 86400, "the last 1,000 motions", "session-x").unwrap();
    sessions::backdate(&id, 4 * 86400);
    sessions::finish_sweep();
    let m = sessions::meta(&id).unwrap();
    assert!(m["finished"].is_null() && m["asked_finish"].is_null(), "neither finished nor asked to be while it waits for its time");
    let said = sessions::inbox(&id).len();

    // Its time comes: told what it was to do, once.
    sessions::wake_due(&id);
    sessions::finish_sweep();
    sessions::finish_sweep();
    let inbox = sessions::inbox(&id);
    let told: Vec<&Value> = inbox[said..].iter().filter(|i| i["text"].as_str().is_some_and(|t| t.contains("the last 1,000 motions"))).collect();
    assert_eq!(told.len(), 1, "told once");
    assert_eq!((told[0]["kind"].as_str(), told[0]["by"].as_str()), (Some("message"), Some("midas")));
    assert!(sessions::meta(&id).unwrap()["wake"].is_null());

    // Ended meanwhile: started again, then told.
    sessions::set_wake(&id, t + 3600, "check the file is whole", "session-x").unwrap();
    sessions::push(&id, &[], Some("stopped"), "runner@x", None, None).unwrap();
    sessions::wake_due(&id);
    sessions::finish_sweep();
    assert_eq!(sessions::meta(&id).unwrap()["status"], "queued");
    assert!(sessions::inbox(&id).last().unwrap()["text"].as_str().unwrap().contains("check the file is whole"));

    // Cancelled on the page; marked done drops what it was to do.
    sessions::set_wake(&id, t + 3600, "later", "ana").unwrap();
    sessions::clear_wake(&id, "ana").unwrap();
    assert!(sessions::clear_wake(&id, "ana").is_err(), "nothing set");
    sessions::set_wake(&id, t + 3600, "later", "ana").unwrap();
    sessions::mark_done(&id, "ana").unwrap();
    assert!(sessions::meta(&id).unwrap()["wake"].is_null());
    let log = sessions::log(&id, 0).unwrap();
    assert!(log["items"].as_array().unwrap().iter().any(|i| i["kind"] == "wake" && i["woken"] == true), "said in its conversation");
}

#[test]
fn a_session_waiting_on_the_person_is_left_alone_and_hears_the_secret_is_set_never_what() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("awaits");
    let t = registry::now();
    assert!(sessions::secret_of("remote:pages", None).is_err(), "a remote the hub lacks says its endpoint");
    assert!(sessions::secret_of("bot:gpu:not a name", None).is_err());
    assert!(sessions::secret_of("vault:x", None).is_err());
    assert_eq!(sessions::secret_of("remote:pages", Some("https://cartopolis.example/mcp")).unwrap()["url"], "https://cartopolis.example/mcp");
    // A bot's secret, whose file is in the scratch state (a remote's is beside it, outside).
    let secret = sessions::secret_of("bot:gpu-1:PAGES_TOKEN", None).unwrap();

    // Landed and idle, nothing left to land: it would finish by itself, but it waits on the person.
    let id = sessions::start("ana", "pages through midas", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[], Some("waiting"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::put_files(&id, &json!({"files": [], "commits": 0, "clean": true})).unwrap();
    assert!(sessions::set_awaits(&id, " ", "", &Value::Null, "session-x").is_err(), "says what");
    sessions::set_awaits(&id, "Paste a cartopolis.org token", "1. Open cartopolis.org/tokens", &secret, "session-x").unwrap();
    sessions::backdate(&id, 4 * 86400);
    sessions::finish_sweep();
    let m = sessions::meta(&id).unwrap();
    assert!(m["finished"].is_null() && m["asked_finish"].is_null(), "neither finished nor asked to be while it waits");

    // Put off, then given: the token goes where it was said, the session hears it is set.
    assert!(sessions::snooze_awaits(&id, t - 5, "ana").is_err());
    sessions::snooze_awaits(&id, t + 3600, "ana").unwrap();
    assert_eq!(sessions::meta(&id).unwrap()["awaits"]["snooze"], t + 3600);
    let said = sessions::inbox(&id).len();
    sessions::give_awaited(&id, "tok-s3cret", "ana").unwrap();
    assert_eq!(crate::botsecrets::for_node("gpu-1").get("PAGES_TOKEN").map(String::as_str), Some("tok-s3cret"));
    assert!(sessions::meta(&id).unwrap()["awaits"].is_null());
    let told = &sessions::inbox(&id)[said..];
    assert_eq!(told.len(), 1);
    let text = told[0]["text"].as_str().unwrap();
    assert!(text.contains("PAGES_TOKEN") && !text.contains("tok-s3cret"), "told it is set, never what: {text}");
    let log = serde_json::to_string(&sessions::log(&id, 0).unwrap()).unwrap();
    assert!(!log.contains("tok-s3cret"), "the value is in no log");
    assert!(sessions::give_awaited(&id, "again", "ana").is_err(), "waits on nothing now");

    // Declined: told to go on without; finished: no longer waits.
    sessions::set_awaits(&id, "Add the A record", "", &Value::Null, "session-x").unwrap();
    assert!(sessions::give_awaited(&id, "x", "ana").is_err(), "nothing to paste");
    sessions::decline_awaited(&id, "ana").unwrap();
    assert!(sessions::inbox(&id).last().unwrap()["text"].as_str().unwrap().contains("will not do"));
    sessions::set_awaits(&id, "Add the A record", "", &Value::Null, "session-x").unwrap();
    sessions::mark_done(&id, "ana").unwrap();
    assert!(sessions::meta(&id).unwrap()["awaits"].is_null());
}

#[test]
fn an_idle_node_somebody_waits_for_goes_back_sooner_and_its_holder_hears() {
    let _g = SERIAL.lock().unwrap();
    scratch("idle-waited");
    assert!(claim("a", "server", None, false));
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0, "heard_since": 0})).unwrap();
    let backdate = |secs: i64| {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(registry::now() - secs);
        reg.mark();
        reg.commit().unwrap();
    };
    backdate(registry::WAITED_IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "nobody waits: half an hour");
    // b waits, but a said it needs the node a while longer.
    assert!(!claim("b", "server", None, true));
    registry::set_intent("a", Some("bench"), Some(15)).unwrap();
    backdate(registry::WAITED_IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "an intent with minutes keeps it");
    registry::set_intent("a", None, None).unwrap();
    backdate(registry::WAITED_IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1"), None, "ten quiet minutes with b waiting");
    let notes = notes_for("a");
    assert_eq!(notes.len(), 1, "{notes:?}");
    assert!(notes[0].starts_with("cpu-1 went back to the pool: nothing ran on it for 10 minutes while somebody waited"), "{}", notes[0]);
    assert!(claim("b", "server", None, true), "and b gets it");
}

#[test]
fn a_landing_tells_the_sessions_changing_its_files() {
    let _g = SERIAL.lock().unwrap();
    scratch("landed-notes");
    let files = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
    crate::collab::report_work("a", Some("feat/a"), &files(&["src/x.rs", "src/z.rs"])).unwrap();
    crate::collab::report_work("b", Some("feat/b"), &files(&["src/x.rs"])).unwrap();
    crate::collab::report_work("c", Some("feat/c"), &files(&["src/y.rs"])).unwrap();
    notes_for("a");
    notes_for("b");
    crate::collab::landed("a", Some("feat/a"), Some("0123456789abcdef"));
    assert_eq!(notes_for("b"), vec!["a landed feat/a (01234567) on main, changing 1 file you change too:\n  src/x.rs\n\
                                     Rebase onto origin/main before you build on it."]);
    assert!(notes_for("c").is_empty(), "c changes none of them");
    assert!(collab_state()["work"]["a"].is_null());
}

#[test]
fn work_of_a_session_long_quiet_overlaps_nobody() {
    let _g = SERIAL.lock().unwrap();
    scratch("overlap-quiet");
    let files = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
    crate::collab::report_work("old", Some("feat/old"), &files(&["src/x.rs"])).unwrap();
    // Its last report three hours ago, and nothing heard of it since.
    let mut st = collab_state();
    st["work"]["old"]["at"] = json!(registry::now() - 3 * 3600);
    set_collab_state(&st);
    crate::collab::forget_seen("old");
    assert!(crate::collab::report_work("new", Some("feat/new"), &files(&["src/x.rs"])).unwrap().is_empty());
    assert!(notes_for("new").is_empty() && notes_for("old").is_empty());
}

#[test]
fn a_deploy_goes_first_in_line_and_an_idle_holder_gives_way_to_it_sooner() {
    let _g = SERIAL.lock().unwrap();
    scratch("deploy-first");
    assert!(claim("a", "server", None, false));
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0, "heard_since": 0})).unwrap();
    let backdate = |secs: i64| {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(registry::now() - secs);
        reg.mark();
        reg.commit().unwrap();
    };
    // A session waits first, then a deploy.
    assert!(!claim("b", "server", None, true));
    assert!(!claim("deployer:server", "server", None, true));
    backdate(registry::DEPLOY_IDLE_S - 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1").as_deref(), Some("a"), "four quiet minutes keep it");
    backdate(registry::DEPLOY_IDLE_S + 60);
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1"), None, "five quiet minutes with a deploy waiting");
    let notes = notes_for("a");
    assert!(notes.iter().any(|n| n.contains("while a deploy or a landing gate waited for it")), "{notes:?}");
    assert!(!claim("b", "server", None, true), "b asked first, but the deploy goes first");
    assert!(claim("deployer:server", "server", None, true));
}

#[test]
fn a_landing_gate_goes_ahead_of_sessions_and_behind_deploys() {
    let _g = SERIAL.lock().unwrap();
    scratch("gate-second");
    assert!(claim("a", "server", None, false));
    registry::write_reading("cpu-1", &json!({"at": registry::now(), "sessions": 0, "heard_since": 0})).unwrap();
    // A session, then a gate, then a deploy wait for the one node.
    assert!(!claim("b", "server", None, true));
    assert!(!claim("gate-c", "server", None, true));
    assert!(!claim("deployer:server", "server", None, true));
    {
        let mut reg = Locked::open().unwrap();
        reg.leases_mut().get_mut("cpu-1").unwrap()["renewed_at"] = json!(registry::now() - registry::DEPLOY_IDLE_S - 60);
        reg.mark();
        reg.commit().unwrap();
    }
    registry::snapshot().unwrap();
    assert_eq!(holder("cpu-1"), None, "five quiet minutes with a gate waiting");
    assert!(!claim("b", "server", None, true), "b asked first, but the gate goes before it");
    assert!(!claim("gate-c", "server", None, true), "and the deploy before the gate");
    assert!(claim("deployer:server", "server", None, true));
    registry::release("deployer:server", None, false).unwrap();
    assert!(!claim("b", "server", None, true));
    assert!(claim("gate-c", "server", None, true));
}

#[test]
fn a_task_left_running_in_the_background_does_not_hold_up_the_finish_the_person_asked_for() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("finish-background");
    let sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    let id = sessions::start("ana", "make the page", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&id, &[json!({"kind": "user", "text": "land it and finish"})], Some("working"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::finish(&id, "session-x", Some(sha), None, false).unwrap();
    // Mid-turn: not cut off.
    sessions::finish_sweep();
    assert!(sessions::meta(&id).unwrap()["finished"].is_null());
    // The turn ended, but a script it started hangs in the background: still "working".
    sessions::push(&id, &[json!({"kind": "turn_end", "reason": "end_turn"}), json!({"kind": "background", "tasks": [{"description": "bun x.ts | head"}], "turn": false})],
        Some("working"), "runner@x", None, None).unwrap();
    sessions::finish_sweep();
    assert_eq!(sessions::meta(&id).unwrap()["finished"]["outcome"], "landed");

    // Nothing to land and idle: a task still running keeps it open (it may be a long run of its own).
    let busy = sessions::start("ana", "sort the motions", None, None, None, None, None, &Value::Null).unwrap();
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&busy, &[json!({"kind": "user", "text": "go"}), json!({"kind": "turn_end"})], Some("working"), "runner@x", Some("conv-2"), None).unwrap();
    sessions::put_files(&busy, &json!({"files": [], "commits": 0, "clean": true})).unwrap();
    sessions::backdate(&busy, 3600);
    sessions::finish_sweep();
    assert!(sessions::meta(&busy).unwrap()["finished"].is_null());
}

#[test]
fn a_machine_reports_its_power_from_its_own_address_only() {
    let _g = SERIAL.lock().unwrap();
    scratch("power");
    let (code, _) = crate::power::record("10.44.0.2", &json!({"w": 12.5, "source": "amdgpu"})).unwrap();
    assert_eq!(code, 204);
    let (code, _) = crate::power::record("10.44.0.9", &json!({"w": 12.5})).unwrap();
    assert_eq!(code, 403, "an address no node has is no machine of the workspace's");
    let (code, _) = crate::power::record("10.44.0.1", &json!({"w": "lots"})).unwrap();
    assert_eq!(code, 400);
    let r = crate::power::read(86400, None);
    let laptop = &r["machines"]["laptop"];
    assert_eq!(laptop["now"]["w"], json!(12.5));
    assert_eq!(laptop["source"], json!("amdgpu"));
    assert!(r["machines"].get("server").is_none(), "nothing was recorded for the server");
}

#[test]
fn a_research_round_goes_only_to_a_runner_that_says_it_can_scout() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("scout-rounds");
    // A goal with a round waiting, as the page leaves it.
    let tree = json!({"seq": 2, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}], "techs": [], "insights": [],
        "rounds": [{"id": "r2", "goal": "g1", "move": "map", "by": "ana", "at": 0, "state": "queued"}]});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    // A session to start, so neither poll waits.
    sessions::start("ana", "fix the layout", None, None, None, None, None, &Value::Null).unwrap();
    let old = sessions::poll("runner@old", &json!({}), true).unwrap();
    assert!(old["scouts"].as_array().unwrap().is_empty(), "a runner built before the tree would take the round and drop it");
    assert_eq!(crate::tree::all()["rounds"][0]["state"], "queued");
    sessions::start("ana", "another", None, None, None, None, None, &Value::Null).unwrap();
    let new = sessions::poll_with("runner@new", &json!({}), true, &["scout"]).unwrap();
    assert_eq!(new["scouts"][0]["round"], "r2");
    assert_eq!(crate::tree::all()["rounds"][0]["state"], "asked");
}

#[test]
fn a_theme_the_scout_proposes_becomes_a_goal_with_its_techs_when_kept() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-themes");
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "hold a call", "name": "Hold a call", "goals": ["g1"], "needs": [], "built": true, "by": "scout", "moves": ["map"]},
                  {"id": "k2", "key": "vote in a poll", "name": "Vote in a poll", "goals": ["g1"], "needs": ["k1"], "built": true, "by": "scout", "moves": ["map"]}],
        "insights": [], "rounds": [{"id": "r3", "goal": "g1", "move": "group", "by": "ana", "at": 0, "state": "asked"}]});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    // The round answers with the names as it was given them, "(built)" and all.
    crate::tree::scouted(&json!({"round": "r3", "goals": [
        {"name": "Meet in the world", "statement": "a community holds its meeting", "techs": ["Hold a call (built)", "Vote in a poll", "Nothing known"]},
        {"name": "Empty", "techs": ["Nothing known"]}]})).unwrap();
    let all = crate::tree::all();
    assert_eq!(all["proposals"].as_array().unwrap().len(), 1, "a theme with no known tech is no theme");
    assert_eq!(all["proposals"][0]["techs"], json!(["k1", "k2"]));
    assert_eq!(all["rounds"][0]["state"], "done");
    let pid = all["proposals"][0]["id"].as_str().unwrap().to_string();
    let after = crate::tree::op(&json!({"op": "proposal_accept", "id": pid}), "ana").unwrap();
    let g = after["goals"].as_array().unwrap().iter().find(|g| g["name"] == "Meet in the world").unwrap().clone();
    assert_eq!(g["parent"], "g1");
    assert_eq!(g["repos"], json!(["acme/cartopolis"]));
    assert!(after["techs"][0]["goals"].as_array().unwrap().contains(&g["id"]));
    assert!(after["proposals"].as_array().unwrap().is_empty());
}

#[test]
fn researching_a_tech_starts_a_session_from_it_once() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-research");
    // A hub with the project the tech is in; put back however the test ends.
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-research-{}.conf", std::process::id()));
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "statement": "talk together", "repos": [], "never": ["ads"]}],
        "techs": [{"id": "k1", "key": "hold a call", "name": "Hold a call", "goals": ["g1"], "needs": [], "built": true, "by": "scout", "moves": ["map"]},
                  {"id": "k2", "key": "vote in a poll", "name": "Vote in a poll", "what": "a poll in a meeting", "who": "an organiser",
                   "goals": ["g1"], "needs": ["k1"], "built": false, "by": "scout", "moves": ["map", "harvest"], "repos": ["acme/cartopolis"]},
                  {"id": "k3", "key": "a guess", "name": "A guess", "goals": ["g1"], "needs": [], "built": false, "by": "scout", "moves": ["map"]}],
        "insights": [{"id": "i4", "goal": "g1", "about": "k2", "text": "polls are not kept", "at": crate::registry::now()}], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    assert!(crate::tree::op(&json!({"op": "research", "id": "k3"}), "ana").is_err(), "a guess is kept first");
    let after = crate::tree::op(&json!({"op": "research", "id": "k2"}), "ana").unwrap();
    let t = after["techs"].as_array().unwrap().iter().find(|t| t["id"] == "k2").unwrap().clone();
    assert_eq!(t["state"], "researching");
    let sid = t["research"]["session"].as_str().unwrap();
    let m = crate::sessions::meta(sid).unwrap();
    assert_eq!(m["repo"], "acme/cartopolis");
    assert!(m["title"].as_str().unwrap_or("").contains("Vote in a poll"), "{}", m["title"]);
    assert!(crate::tree::op(&json!({"op": "research", "id": "k2"}), "ana").is_err(), "one session on a tech at a time");
}

#[test]
fn built_techs_are_photographed_one_after_another_and_keep_the_pictures() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-photos");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-photos-{}.conf", std::process::id()));
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "hold a call", "name": "Hold a call", "what": "a call", "goals": ["g1"], "needs": [], "built": true, "by": "scout", "moves": ["map"]},
                  {"id": "k2", "key": "recover chats", "name": "Recover chats", "goals": ["g1"], "needs": [], "built": true, "by": "scout", "moves": ["map"]},
                  {"id": "k3", "key": "vote", "name": "Vote", "goals": ["g1"], "needs": [], "built": false, "by": "scout", "moves": ["map", "harvest"]}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    assert!(crate::tree::op(&json!({"op": "photograph", "id": "k3"}), "ana").is_err(), "what is not built is photographed by its builder");
    let all = crate::tree::op(&json!({"op": "photograph_all"}), "ana").unwrap();
    assert_eq!(all["photos"]["queue"], json!(["k1", "k2"]));
    // One at a time: the first starts, the second waits for it.
    crate::tree::tick();
    let all = crate::tree::all();
    let sid = all["techs"][0]["photograph"]["session"].as_str().unwrap().to_string();
    assert_eq!(all["techs"][0]["photographing"], true);
    assert_eq!(all["photos"]["queue"], json!(["k2"]));
    let m = crate::sessions::meta(&sid).unwrap();
    assert_eq!(m["repo"], "acme/cartopolis");
    assert!(m["title"].as_str().unwrap_or("").contains("Hold a call"), "{}", m["title"]);
    crate::tree::tick();
    assert_eq!(crate::tree::all()["photos"]["queue"], json!(["k2"]), "waits while one is photographed");
    assert!(crate::tree::op(&json!({"op": "photograph", "id": "k1"}), "ana").is_err(), "one session photographing it at a time");
    // Its pictures: kept on the tech; what is no picture is not.
    assert!(crate::tree::add_shot("k1", &sid, "1-call.png", Some("A call"), b"<html>").is_err());
    crate::tree::add_shot("k1", &sid, "1-call.png", Some("The call screen"), b"\x89PNG\r\n\x1a\nx").unwrap();
    crate::tree::add_shot("k1", &sid, "2-call.jpg", Some("Muted"), &[0xff, 0xd8, 0xff, 0]).unwrap();
    let shots = crate::tree::all()["techs"][0]["shots"].clone();
    assert_eq!(shots.as_array().unwrap().len(), 2);
    assert_eq!(shots[0]["caption"], "The call screen");
    assert!(crate::tree::shot_path("k1", "2").unwrap().ends_with("hosted/shots/k1/2.jpg"));
    assert_eq!(crate::tree::shot_path("../k1", "2"), None);
    // A later session's pictures replace an earlier one's.
    crate::tree::add_shot("k1", "s999", "1-new.png", None, b"\x89PNG\r\n\x1a\ny").unwrap();
    let shots = crate::tree::all()["techs"][0]["shots"].clone();
    assert_eq!(shots.as_array().unwrap().len(), 1);
    assert!(!crate::tree::shot_path("k1", "1").unwrap().exists(), "the old picture's file goes too");
    crate::tree::op(&json!({"op": "shot_drop", "id": "k1", "n": 3}), "ana").unwrap();
    assert!(crate::tree::all()["techs"][0]["shots"].as_array().unwrap().is_empty());
    crate::tree::op(&json!({"op": "photograph_stop"}), "ana").unwrap();
    assert_eq!(crate::tree::all()["photos"]["queue"], json!([]));
}

#[test]
fn a_sketch_draws_a_techs_mockup_without_bringing_it_out_of_the_fog() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-sketch");
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "notices", "name": "Notices", "what": "a ping while shut", "goals": ["g1"], "needs": [], "built": false, "by": "scout", "moves": ["map"]}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    crate::tree::op(&json!({"op": "scout", "goal": "g1", "move": "sketch"}), "ana").unwrap();
    let jobs = crate::tree::rounds_take();
    assert_eq!(jobs[0]["draw"], json!(["k1 Notices: a ping while shut"]));
    let rid = jobs[0]["round"].as_str().unwrap();
    // The runner photographed the page: a PNG in base64, kept by the tech's id; what is no PNG is not kept.
    let png = data_encoding::BASE64.encode(b"\x89PNG\r\n\x1a\nnot really a picture");
    crate::tree::scouted(&json!({"round": rid, "techs": [
        {"id": "k1", "name": "Notices", "frame": "wide", "png": png},
        {"id": "k1", "name": "Notices", "png": data_encoding::BASE64.encode(b"<html>")},
        {"name": "Something new", "state": "missing"}]})).unwrap();
    let all = crate::tree::all();
    assert_eq!(all["techs"].as_array().unwrap().len(), 1, "a sketch adds no techs");
    assert_eq!(all["techs"][0]["state"], "fog", "a drawing is no second finding");
    assert_eq!(all["techs"][0]["mockup_frame"], "wide");
    let file = crate::tree::mockup_png_path("k1").unwrap();
    assert!(std::fs::read(&file).unwrap().starts_with(b"\x89PNG"));
    assert!(crate::tree::op(&json!({"op": "scout", "goal": "g1", "move": "sketch"}), "ana").is_err(), "nothing left to draw");
    crate::tree::op(&json!({"op": "scout", "goal": "g1", "move": "sketch", "tech": "k1"}), "ana").unwrap();
}

#[test]
fn a_look_runs_the_moves_that_fit_one_after_another() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-look");
    // A theme without projects of its own, under a goal that names one; one tech to build, already drawn.
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]},
                                        {"id": "g2", "name": "meet", "parent": "g1", "repos": []}],
        "techs": [{"id": "k1", "key": "notices", "name": "Notices", "goals": ["g2"], "needs": [], "built": false, "by": "scout", "moves": ["map"], "mockup": "<svg/>"}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    let all = crate::tree::op(&json!({"op": "look", "goal": "g2", "focus": "calls"}), "ana").unwrap();
    let look: Vec<&Value> = all["rounds"].as_array().unwrap().iter().collect();
    assert_eq!(look.iter().map(|r| r["move"].as_str().unwrap()).collect::<Vec<_>>(), ["map", "harvest", "group", "sketch"]);
    let lid = look[0]["id"].clone();
    assert!(look.iter().all(|r| r["look"] == lid));
    // A second look waits for the first, and starts by itself after it; taken back, it is not done.
    let all = crate::tree::op(&json!({"op": "look", "goal": "g2", "focus": "screens", "via": "talk"}), "ana").unwrap();
    let second = all["rounds"].as_array().unwrap()[4].clone();
    assert_eq!(second["after"], look[3]["id"]);
    assert_eq!(second["via"], "talk");
    crate::tree::op(&json!({"op": "look_stop", "look": second["id"]}), "ana").unwrap();
    for _ in 0..3 {
        crate::tree::op(&json!({"op": "look", "goal": "g2"}), "ana").unwrap();
    }
    assert!(crate::tree::op(&json!({"op": "look", "goal": "g2"}), "ana").is_err(), "three wait at most");
    let all = crate::tree::all();
    for r in all["rounds"].as_array().unwrap().iter().skip(4) {
        let _ = crate::tree::op(&json!({"op": "look_stop", "look": r["look"]}), "ana");
    }

    // One move at a time, the theme reading its goal's project.
    let jobs = crate::tree::rounds_take();
    assert_eq!(jobs.len(), 1);
    assert_eq!(jobs[0]["move"], "map");
    assert_eq!(jobs[0]["goal"]["repos"], json!(["acme/cartopolis"]));
    assert_eq!(jobs[0]["focus"], "calls");
    assert!(crate::tree::rounds_take().is_empty(), "harvest waits for map");
    let map = jobs[0]["round"].as_str().unwrap().to_string();
    // While it reads, what it reads is on the round; once back, only how much.
    crate::tree::scouting(&json!({"round": map, "lines": [{"kind": "read", "text": "crates/calls/src/sfu.rs", "repo": "cartopolis", "at": 1}],
        "thought": "Calls exist; screen sharing does not.", "reads": 14, "searches": 6})).unwrap();
    let r = crate::tree::all()["rounds"][0].clone();
    assert_eq!(r["live"]["lines"][0]["text"], "crates/calls/src/sfu.rs");
    assert_eq!(r["live"]["thought"], "Calls exist; screen sharing does not.");
    crate::tree::scouted(&json!({"round": map, "techs": [{"name": "Polls", "state": "missing"}, {"name": "Notices", "state": "built"}]})).unwrap();
    let r = crate::tree::all()["rounds"][0].clone();
    assert_eq!(r["live"]["lines"], json!([]));
    assert_eq!(r["live"]["reads"], 14);
    assert_eq!(r["changed"]["built"], json!(["k1"]));
    assert_eq!(r["changed"]["added"].as_array().unwrap().len(), 1);

    let jobs = crate::tree::rounds_take();
    assert_eq!(jobs[0]["move"], "harvest");
    crate::tree::scouted(&json!({"round": jobs[0]["round"], "techs": []})).unwrap();
    // Group: a theme of two techs needs no sorting, so it is skipped; Sketch then has Polls to draw.
    let jobs = crate::tree::rounds_take();
    assert_eq!(jobs[0]["move"], "sketch");
    let all = crate::tree::all();
    assert_eq!(all["rounds"][2]["state"], "skipped");

    // Stopped: what is on its way is not kept.
    crate::tree::op(&json!({"op": "look_stop", "look": lid}), "ana").unwrap();
    crate::tree::scouted(&json!({"round": jobs[0]["round"], "techs": [{"name": "Something", "state": "missing"}]})).unwrap();
    let all = crate::tree::all();
    assert_eq!(all["rounds"][3]["state"], "stopped");
    assert_eq!(all["techs"].as_array().unwrap().len(), 2);
    crate::tree::op(&json!({"op": "look_seen", "look": lid}), "ana").unwrap();
    assert_eq!(crate::tree::all()["rounds"][0]["seen"], json!(["ana"]));

    // About one tech: one move, its question in the focus.
    let all = crate::tree::op(&json!({"op": "look", "goal": "g2", "tech": "k1", "ask": "smaller"}), "ana").unwrap();
    let r = all["rounds"].as_array().unwrap().last().unwrap().clone();
    assert_eq!(r["move"], "map");
    assert_eq!(r["about"], "k1");
    assert!(r["focus"].as_str().unwrap().contains("Notices"));
}

#[test]
fn a_tech_talked_over_changes_its_words_and_is_drawn_again_with_the_remarks() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-talk");
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "meet", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "share a screen", "name": "Share a screen", "what": "Show your screen.", "who": "Anyone in a call",
                   "goals": ["g1"], "needs": [], "built": false, "by": "scout", "moves": ["map"], "size": "M"},
                  {"id": "k2", "key": "polls", "name": "Polls", "goals": ["g1"], "needs": [], "built": false, "by": "scout", "moves": ["map"]}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();

    // Only the fields given change, each with what it was.
    let all = crate::tree::op(&json!({"op": "tech_edit", "id": "k1", "who": "The one who leads a meeting"}), "ana").unwrap();
    let t = &all["techs"][0];
    assert_eq!(t["who"], "The one who leads a meeting");
    assert_eq!(t["what"], "Show your screen.");
    assert_eq!(t["edited"]["who"]["was"], "Anyone in a call");
    assert!(crate::tree::op(&json!({"op": "tech_edit", "id": "k1", "name": "Polls"}), "ana").is_err(), "a name another tech has");
    assert!(crate::tree::op(&json!({"op": "tech_edit", "id": "k1", "size": "XL"}), "ana").is_err());
    assert!(crate::tree::op(&json!({"op": "tech_edit", "id": "k1"}), "ana").is_err(), "nothing to change");
    let all = crate::tree::op(&json!({"op": "tech_edit", "id": "k1", "name": "Share a screen in a meeting"}), "ana").unwrap();
    assert_eq!(all["techs"][0]["key"], crate::tree::key("Share a screen in a meeting"));

    // Two remarks, one taken back; the drawing is given the description and the remark that is left.
    crate::tree::op(&json!({"op": "remark", "id": "k1", "text": "The button goes in the call bar"}), "ana").unwrap();
    let all = crate::tree::op(&json!({"op": "remark", "id": "k1", "text": "Bigger"}), "ana").unwrap();
    let m2 = all["techs"][0]["remarks"][1]["id"].clone();
    crate::tree::op(&json!({"op": "remark_drop", "id": "k1", "remark": m2}), "ana").unwrap();
    crate::tree::op(&json!({"op": "scout", "goal": "g1", "move": "sketch", "tech": "k1"}), "ana").unwrap();
    let jobs = crate::tree::rounds_take();
    let draw = jobs[0]["draw"][0].as_str().unwrap();
    assert!(draw.contains("The one who leads a meeting") && draw.contains("The button goes in the call bar") && !draw.contains("Bigger"));

    // A remark made while it draws waits for the next drawing.
    crate::tree::op(&json!({"op": "remark", "id": "k1", "text": "Show who shares"}), "ana").unwrap();
    let png = data_encoding::BASE64.encode(b"\x89PNG\r\n\x1a\nrest");
    crate::tree::scouted(&json!({"round": jobs[0]["round"], "techs": [{"id": "k1", "name": "Share a screen in a meeting", "png": png,
        "shows": "A call with the share button in its bar."}]})).unwrap();
    // A guess nobody started and no look found again in a month fades with nobody's word; brought back, it is a guess again.
    let old = json!({"id": "k3", "key": "old guess", "name": "Old guess", "goals": ["g1"], "needs": [], "built": false, "by": "scout", "moves": ["map"], "at": 1});
    let mut v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    v["techs"].as_array_mut().unwrap().push(old);
    std::fs::write(&path, v.to_string()).unwrap();
    let all = crate::tree::all();
    assert_eq!(all["techs"][2]["state"], "dropped");
    assert_eq!(all["techs"][2]["faded"], true);
    assert_eq!(all["techs"][1]["state"], "fog", "a guess with no time on record does not fade");
    let all = crate::tree::op(&json!({"op": "tech_restore", "id": "k3"}), "ana").unwrap();
    assert_eq!(all["techs"][2]["state"], "fog");
    let t = crate::tree::all()["techs"][0].clone();
    assert_eq!(t["mockup_shows"], "A call with the share button in its bar.");
    assert_eq!(t["remarks"].as_array().unwrap().iter().map(|m| m["text"].as_str().unwrap()).collect::<Vec<_>>(), ["Show who shares"]);
}

#[test]
fn a_direction_researches_the_techs_on_the_way_one_after_another() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("tree-direction");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-direction-{}.conf", std::process::id()));
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    let tech = |id: &str, needs: Value, built: bool, moves: Value, size: &str| json!({"id": id, "key": id, "name": format!("Tech {id}"), "goals": ["g1"],
        "needs": needs, "built": built, "by": "scout", "moves": moves, "size": size, "repos": ["acme/cartopolis"]});
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [tech("k1", json!([]), true, json!(["map"]), "M"), tech("k2", json!(["k1"]), false, json!(["map", "harvest"]), "L"),
                  tech("k3", json!(["k2"]), false, json!(["map"]), "S"), tech("k4", json!([]), false, json!(["map"]), "S")],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    // Toward k3: k2, then k3; k4 is off the way.
    crate::tree::op(&json!({"op": "direction_set", "target": "k3"}), "ana").unwrap();
    assert_eq!(crate::tree::all()["directions"][0]["next"], json!({"tech": "k2", "why": "soon", "project": "acme/cartopolis"}), "ready: it starts at the next look");
    crate::tree::tick();
    let all = crate::tree::all();
    let k2 = &all["techs"][1];
    assert_eq!(k2["state"], "researching", "the next tech on the way is started");
    let sid = k2["research"]["session"].as_str().unwrap().to_string();
    assert!(all["techs"][3]["research"].is_null(), "off the way");
    // The session is named for its tech and carries it, for the lists; the tech counts it.
    let meta = sessions::meta(&sid).unwrap();
    assert_eq!(meta["title"], "Tech k2");
    assert_eq!(meta["research"]["tech"], "k2");
    assert_eq!(meta["research"]["goal"], "communities");
    assert_eq!(k2["sessions"][0]["id"], json!(sid));
    assert_eq!(k2["sessions"][0]["outcome"], Value::Null);
    assert!(k2["sessions"][0]["at"].as_i64().is_some(), "when it started, for the progress: {}", k2["sessions"]);
    // k3 needs k2, which is at work: next, after it.
    assert_eq!(all["directions"][0]["next"], json!({"tech": "k3", "why": "after", "after": "k2", "project": "acme/cartopolis"}));
    crate::tree::tick();
    assert_eq!(crate::tree::all()["directions"][0]["runs"].as_array().unwrap().len(), 1, "one at a time");
    // Its session lands: k2 is built, and k3 — a guess, on the way the person chose — is next.
    let sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&sid, &[], Some("working"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::finish(&sid, "session-x", Some(sha), None, false).unwrap();
    sessions::push(&sid, &[], Some("waiting"), "runner@x", None, None).unwrap();
    sessions::finish_sweep();
    crate::tree::tick();
    let all = crate::tree::all();
    assert_eq!(all["techs"][1]["built"], true);
    assert_eq!(all["techs"][2]["state"], "researching");
    assert!(all["techs"][2]["confirmed_by"].as_str().unwrap().starts_with("direction"));
    // It is dropped unlanded, and the retry too: the direction pauses rather than go on spending.
    for _ in 0..2 {
        let s = crate::tree::all()["techs"][2]["research"]["session"].as_str().unwrap().to_string();
        sessions::finish(&s, "ana", None, None, true).unwrap();
        crate::tree::tick();
    }
    let all = crate::tree::all();
    let d = all["directions"][0].clone();
    assert!(d["paused"].as_str().unwrap().contains("landed nothing"), "{d}");
    assert_eq!(d["next"]["why"], "paused");
    assert_eq!(all["techs"][1]["sessions"][0]["outcome"], "landed");
    // k3 was tried twice, oldest first, both dropped.
    let k3: Vec<&str> = all["techs"][2]["sessions"].as_array().unwrap().iter().map(|s| s["outcome"].as_str().unwrap_or("going")).collect();
    assert_eq!(k3, ["dropped", "dropped"]);
}

#[test]
fn a_direction_sends_the_scout_when_its_way_runs_out_and_is_reached_when_it_finds_nothing() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-direction-scout");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-direction-scout-{}.conf", std::process::id()));
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    // Everything known toward g1 is built: the old direction would have called it reached at once.
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "k1", "name": "Tech k1", "goals": ["g1"], "needs": [], "built": true, "by": "scout",
                   "moves": ["map"], "size": "S", "repos": ["acme/cartopolis"]}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    crate::tree::op(&json!({"op": "direction_set", "target": "g1", "at_once": 9, "per_day": 0}), "ana").unwrap();
    let d = crate::tree::all()["directions"][0].clone();
    assert_eq!((d["at_once"].as_u64(), d["per_day"].as_u64(), d["scout"].as_bool()), (Some(3), Some(1), Some(true)), "limits within bounds: {d}");
    crate::tree::op(&json!({"op": "direction_limits", "at_once": 2, "per_day": 6, "scout_every": 0}), "ana").unwrap();
    let d = crate::tree::all()["directions"][0].clone();
    assert_eq!((d["at_once"].as_u64(), d["per_day"].as_u64(), d["scout_every"].as_u64()), (Some(2), Some(6), Some(0)), "changed in place: {d}");
    assert!(d["reached"].is_null() && d["runs"].as_array().unwrap().is_empty());
    // The way has run out: the scout is sent along it, a whole look, and nothing is reached while it looks.
    crate::tree::tick();
    let all = crate::tree::all();
    let rounds: Vec<&str> = all["rounds"].as_array().unwrap().iter().map(|r| r["move"].as_str().unwrap()).collect();
    assert_eq!(rounds, ["map", "harvest", "group", "sketch"]);
    assert!(all["rounds"].as_array().unwrap().iter().all(|r| r["via"] == "direction" && r["goal"] == "g1"));
    assert_eq!(all["directions"][0]["scouted"]["why"], "out");
    assert_eq!(all["directions"][0]["next"]["why"], "scouting");
    assert!(all["directions"][0]["reached"].is_null());
    crate::tree::tick();
    assert_eq!(crate::tree::all()["rounds"].as_array().unwrap().len(), 4, "one look for one running out");
    // The look comes back with nothing new: then, and only then, the goal is reached.
    let mut v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    for r in v["rounds"].as_array_mut().unwrap() {
        r["state"] = json!("done");
    }
    std::fs::write(&path, v.to_string()).unwrap();
    crate::tree::tick();
    let d = crate::tree::all()["directions"][0].clone();
    assert!(d["reached"].as_i64().is_some(), "{d}");
    assert_eq!(crate::tree::all()["rounds"].as_array().unwrap().len(), 4, "no second look for the same running out");
}

#[test]
fn directions_go_side_by_side_within_one_budget_taking_turns_in_a_project() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("tree-directions");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-directions-{}.conf", std::process::id()));
    let repos = vec!["acme/cartopolis".into(), "acme/pinnacle".into(), "acme/mithril".into()];
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos, ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    let tech = |id: &str, goal: &str, repo: &str, size: &str| json!({"id": id, "key": id, "name": format!("Tech {id}"), "goals": [goal],
        "needs": [], "built": false, "by": "person", "moves": ["map"], "size": size, "repos": [repo]});
    let mut k3 = tech("k3", "g2", "acme/pinnacle", "S");
    k3["lands_in"] = json!(["acme/mithril", "acme/pinnacle"]);
    // A tree from before there were several directions: its one direction, toward g1.
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]},
                                          {"id": "g2", "name": "an os", "repos": ["acme/pinnacle", "acme/mithril"]}],
        "techs": [tech("k1", "g1", "acme/cartopolis", "S"), tech("k2", "g1", "acme/cartopolis", "M"), k3, tech("k4", "g2", "acme/pinnacle", "M")],
        "insights": [], "rounds": [],
        "direction": {"target": "g1", "name": "communities", "by": "ana", "at": 1, "at_once": 2, "per_day": 4, "scout": false,
                      "paused": null, "reached": null, "resumed_at": 1, "runs": []}});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    let all = crate::tree::all();
    assert_eq!(all["directions"][0]["id"], "d0", "the old direction is the first of the list");
    assert!(all["direction"].is_null());
    assert_eq!((all["budget"]["at_once"].as_u64(), all["budget"]["per_project"].as_u64()), (Some(3), Some(1)));
    let research = |all: &Value, id: &str| all["techs"].as_array().unwrap().iter().find(|t| t["id"] == id).unwrap()["research"]["session"].as_str().map(str::to_string);
    // The first goes: k1 in cartopolis.
    crate::tree::tick();
    let all = crate::tree::all();
    assert!(research(&all, "k1").is_some());
    // A second direction, beside it, not in its place.
    crate::tree::op(&json!({"op": "direction_set", "target": "g2", "at_once": 2, "scout": false}), "ana").unwrap();
    let all = crate::tree::all();
    let d2 = all["directions"][1]["id"].as_str().unwrap().to_string();
    assert!(all["directions"][0]["cleared"].is_null(), "both go");
    // k2 waits for cartopolis, where k1 is at work; g2's k3 starts in mithril, the project it lands in first.
    crate::tree::tick();
    let all = crate::tree::all();
    assert!(research(&all, "k2").is_none(), "one session per project");
    assert_eq!(all["directions"][0]["next"]["why"], "project");
    assert_eq!(all["directions"][0]["next"]["project"], "acme/cartopolis");
    let s3 = research(&all, "k3").expect("k3 started");
    let m3 = sessions::meta(&s3).unwrap();
    assert_eq!(m3["repo"], "acme/mithril");
    assert!(m3["prompt"].as_str().unwrap().contains("acme/mithril, then acme/pinnacle"), "{}", m3["prompt"]);
    // k4 in pinnacle: the third at once, which is all the budget allows.
    crate::tree::tick();
    let all = crate::tree::all();
    assert!(research(&all, "k4").is_some());
    assert_eq!(all["budget"]["going"], 3);
    crate::tree::op(&json!({"op": "budget_set", "at_once": 9, "per_project": 0}), "ana").unwrap();
    assert_eq!((crate::tree::all()["budget"]["at_once"].as_u64(), crate::tree::all()["budget"]["per_project"].as_u64()), (Some(6), Some(1)));
    crate::tree::op(&json!({"op": "budget_set", "at_once": 3}), "ana").unwrap();
    // k3's part in mithril lands: not built yet, its part in pinnacle is next.
    let sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&s3, &[], Some("working"), "runner@x", Some("conv-3"), None).unwrap();
    sessions::finish(&s3, "session-x", Some(sha), None, false).unwrap();
    sessions::push(&s3, &[], Some("waiting"), "runner@x", None, None).unwrap();
    sessions::finish_sweep();
    crate::tree::tick();
    let all = crate::tree::all();
    let t3 = all["techs"].as_array().unwrap().iter().find(|t| t["id"] == "k3").unwrap().clone();
    assert_eq!(t3["built"], false, "{t3}");
    assert_eq!(t3["landed_in"], json!(["acme/mithril"]));
    assert_eq!(all["directions"][1]["next"]["project"], "acme/pinnacle", "{}", all["directions"][1]["next"]);
    // The order is the person's: g2 first.
    crate::tree::op(&json!({"op": "direction_order", "ids": [d2, "d0"]}), "ana").unwrap();
    assert_eq!(crate::tree::all()["directions"][0]["id"], json!(d2));
    // Stopping one by id leaves the other going.
    crate::tree::op(&json!({"op": "direction_clear", "id": "d0"}), "ana").unwrap();
    let all = crate::tree::all();
    assert!(all["directions"][1]["cleared"].is_object() && all["directions"][0]["cleared"].is_null());
}

#[test]
fn a_research_brief_says_when_it_is_done_and_how_to_work() {
    let _g = SERIAL.lock().unwrap();
    scratch("tree-brief-done");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-brief-done-{}.conf", std::process::id()));
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "k1", "name": "Invite by a link", "goals": ["g1"], "needs": [], "built": false, "by": "person",
                   "moves": ["map"], "size": "S", "repos": ["acme/cartopolis"], "done": "a link opens the community on the phone"}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    crate::tree::op(&json!({"op": "research", "id": "k1"}), "ana").unwrap();
    let sid = crate::tree::all()["techs"][0]["research"]["session"].as_str().unwrap().to_string();
    let brief = crate::sessions::meta(&sid).unwrap()["prompt"].as_str().unwrap().to_string();
    assert!(brief.contains("Done when: a link opens the community on the phone"), "{brief}");
    assert!(brief.contains("How to work:") && brief.contains("CLAUDE.md"), "{brief}");
    assert!(brief.contains("one check at a time"), "{brief}");
    // The person's words for it can be edited like the rest of the tech.
    crate::tree::op(&json!({"op": "tech_edit", "id": "k1", "done": "the link works without an account"}), "ana").unwrap();
    assert_eq!(crate::tree::all()["techs"][0]["done"], "the link works without an account");
}

#[test]
fn a_research_started_by_hand_that_lands_builds_its_tech() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("tree-research-lands");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    let conf = std::env::temp_dir().join(format!("midas-test-tree-research-lands-{}.conf", std::process::id()));
    std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    // No direction: the research is the person's Start now.
    let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
        "techs": [{"id": "k1", "key": "k1", "name": "Invite by a link", "goals": ["g1"], "needs": [], "built": false, "by": "scout",
                   "moves": ["map", "harvest"], "size": "S", "repos": ["acme/cartopolis"]}],
        "insights": [], "rounds": []});
    let path = crate::registry::root().join("hosted").join("tree.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, tree.to_string()).unwrap();
    crate::tree::op(&json!({"op": "research", "id": "k1"}), "ana").unwrap();
    let sid = crate::tree::all()["techs"][0]["research"]["session"].as_str().unwrap().to_string();
    crate::tree::tick();
    assert_eq!(crate::tree::all()["techs"][0]["state"], "researching");
    let sha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678";
    sessions::poll("runner@x", &json!({}), true).unwrap();
    sessions::push(&sid, &[], Some("working"), "runner@x", Some("conv-1"), None).unwrap();
    sessions::finish(&sid, "session-x", Some(sha), None, false).unwrap();
    sessions::push(&sid, &[], Some("waiting"), "runner@x", None, None).unwrap();
    sessions::finish_sweep();
    crate::tree::tick();
    let k1 = &crate::tree::all()["techs"][0];
    assert_eq!(k1["state"], "built", "a landing built it, with no direction to read it back: {k1}");
    assert_eq!(k1["built_by"], "research");
    // Not built after all, on the person's word: the old landing does not build it again.
    crate::tree::op(&json!({"op": "tech_built", "id": "k1", "built": false}), "ana").unwrap();
    crate::tree::tick();
    assert_eq!(crate::tree::all()["techs"][0]["built"], false);
}

#[test]
fn a_node_free_for_an_hour_sleeps_and_wakes_when_somebody_waits() {
    let _g = SERIAL.lock().unwrap();
    scratch("sleep");
    let asleep = || Locked::open().unwrap().node("gpu-1").unwrap()["asleep"].is_object();
    let answer = |vms: Value| crate::sleep::host("10.44.0.2", &json!({"vms": vms})).unwrap().1;
    // The laptop runs gpu-1; it cannot answer for the server's node.
    assert_eq!(answer(json!(["gpu-1", "cpu-1"])), json!({"nodes": {"gpu-1": "run"}}));
    crate::sleep::tick().unwrap();
    assert!(!asleep(), "free just now");
    {
        let mut reg = Locked::open().unwrap();
        reg.state["sleep"]["gpu-1"]["free_since"] = json!(registry::now() - crate::sleep::IDLE_S - 1);
        reg.mark();
        reg.commit().unwrap();
    }
    crate::sleep::tick().unwrap();
    assert!(asleep(), "free for an hour");
    assert_eq!(answer(json!(["gpu-1"])), json!({"nodes": {"gpu-1": "sleep"}}));
    assert!(Locked::open().unwrap().node("cpu-1").unwrap()["asleep"].is_null(), "no machine stops the server's node");
    // Its heartbeat stops; somebody wants a laptop node and waits.
    registry::set_online("gpu-1", false, "test").unwrap();
    assert!(!claim("waiter", "laptop", None, true));
    crate::sleep::tick().unwrap();
    assert!(!asleep(), "a waiter wakes it");
    assert_eq!(answer(json!(["gpu-1"])), json!({"nodes": {"gpu-1": "run"}}));
}

#[test]
fn a_held_node_never_sleeps_and_a_machine_gone_quiet_leaves_its_nodes_awake() {
    let _g = SERIAL.lock().unwrap();
    scratch("sleep-held");
    let asleep = || Locked::open().unwrap().node("gpu-1").unwrap()["asleep"].is_object();
    let old = |reg: &mut Locked| {
        reg.state["sleep"]["gpu-1"]["free_since"] = json!(registry::now() - crate::sleep::IDLE_S - 1);
        reg.mark();
        reg.commit().unwrap();
    };
    crate::sleep::host("10.44.0.2", &json!({"vms": ["gpu-1"]})).unwrap();
    crate::sleep::tick().unwrap();
    assert!(claim("a", "laptop", None, false));
    crate::sleep::tick().unwrap();
    assert!(Locked::open().unwrap().state["sleep"]["gpu-1"].is_null(), "a lease resets the hour");
    registry::release("a", None, false).unwrap();
    crate::sleep::tick().unwrap();
    old(&mut Locked::open().unwrap());
    crate::sleep::tick().unwrap();
    assert!(asleep());
    // The machine stops asking (its power job died): nobody could wake the node, so it is not left asleep.
    {
        let mut reg = Locked::open().unwrap();
        reg.state["sleep_hosts"]["laptop"]["at"] = json!(registry::now() - 600);
        reg.mark();
        reg.commit().unwrap();
    }
    crate::sleep::tick().unwrap();
    assert!(!asleep());
}

#[test]
fn a_fast_gpu_node_goes_before_a_slow_one_without() {
    let _g = SERIAL.lock().unwrap();
    scratch("fast-gpu");
    // The Macs are GPU nodes and four times as fast as the CPU node: speed
    // decides, the GPU only between nodes as fast.
    let ts = chrono::Utc::now().to_rfc3339();
    let mut lines = String::new();
    for (node, machine, secs) in [("cpu-1", "server", 900), ("cpu-1", "server", 880), ("gpu-1", "laptop", 210), ("gpu-1", "laptop", 220)] {
        lines += &format!("{}\n", json!({"ts": ts, "node": node, "machine": machine, "actor": "s", "shape": "cargo test",
            "seconds": secs, "exit": 0, "first_build_in_lease": false}));
    }
    std::fs::write(registry::root().join("builds.jsonl"), lines).unwrap();
    assert!(claim("a", "any", None, false));
    assert_eq!(holder("gpu-1").as_deref(), Some("a"), "the fastest free node, GPU or not");
    assert!(claim("b", "any", None, false));
    assert_eq!(holder("cpu-1").as_deref(), Some("b"));
}

#[test]
fn a_free_gpu_node_somebody_waits_for_is_theirs() {
    let _g = SERIAL.lock().unwrap();
    scratch("gpu-kept");
    assert!(claim("x", "any", Some("cpu-1"), false));
    assert!(claim("x2", "gpu", None, false));
    assert!(!claim("w", "gpu", None, true), "both taken: w waits for a GPU");
    registry::release("x2", None, false).unwrap();
    assert!(!claim("a", "any", None, false), "the freed GPU node is queued behind w");
    assert!(claim("w", "gpu", None, true));
}

// ── Repositories the hub hosts (hosted.rs) ───────────────────────────────────

fn sh(dir: &std::path::Path, args: &[&str]) -> String {
    let out = std::process::Command::new("git").arg("-C").arg(dir).args(args)
        .env("GIT_AUTHOR_NAME", "t").env("GIT_AUTHOR_EMAIL", "t@t").env("GIT_COMMITTER_NAME", "t").env("GIT_COMMITTER_EMAIL", "t@t")
        .output().unwrap();
    assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

fn new_project(name: &str, public: bool) -> serde_json::Value {
    crate::hosted::create(&crate::hosted::New {
        owner: "acme", name, description: "A test project", public, gate: Some("true"), gate_nodes: None, by: "test",
    }).unwrap()
}

#[test]
fn a_new_project_is_a_hosted_repository_with_a_main_and_a_landing() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-create");
    let v = new_project("widget", false);
    assert_eq!(v["repo"], "acme/widget");
    let dir = crate::hosted::path("acme/widget");
    assert!(dir.join("hooks/pre-receive").exists() && dir.join("hooks/post-receive").exists());
    assert_eq!(sh(&dir, &["show", "main:README.md"]), "# widget\n\nA test project");
    assert!(crate::hosted::create(&crate::hosted::New {
        owner: "acme", name: "widget", description: "", public: false, gate: None, gate_nodes: None, by: "test",
    }).is_err(), "never twice");
    assert!(crate::hosted::create(&crate::hosted::New {
        owner: "acme", name: "../x", description: "", public: false, gate: None, gate_nodes: None, by: "test",
    }).is_err(), "a name does not walk out");
    // The workspace sees it as a project like any other.
    let conf = crate::conf::hub();
    assert!(conf.allows("acme/widget.git"));
    let p = conf.project("acme/widget").unwrap();
    assert_eq!((p["gate"].as_str(), p["host"].as_str(), p["main"].as_str()), (Some("true"), Some("midas"), Some("main")));
    assert_eq!(crate::mirror::mirror_path("acme/widget.git"), dir, "its own mirror");
    let listed = crate::sessions::projects();
    let w = listed.as_array().unwrap().iter().find(|p| p["repo"] == "acme/widget").unwrap();
    assert!(w["git"].as_str().unwrap().starts_with("midas@") && w["hosted"] == true, "{w}");
    // Reading without a checkout.
    assert_eq!(crate::hosted::show("acme/widget", None, "").unwrap()["entries"][0]["name"], "README.md");
    assert_eq!(crate::hosted::log("acme/widget", None, 5).unwrap().len(), 1);
}

#[test]
fn an_agent_moves_main_only_forward_from_the_landing_with_a_pass() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-push");
    new_project("gadget", false);
    let dir = crate::hosted::path("acme/gadget");
    let old = sh(&dir, &["rev-parse", "main"]);
    // A commit on top of main, and one beside it, made in the bare repository.
    let tree = sh(&dir, &["rev-parse", "main^{tree}"]);
    let on_top = sh(&dir, &["commit-tree", &tree, "-p", &old, "-m", "on top"]);
    let beside = sh(&dir, &["commit-tree", &tree, "-m", "beside"]);
    fn to<'a>(old: &'a str, new: &'a str) -> Vec<crate::hosted::Update<'a>> {
        vec![crate::hosted::Update { old, new, refname: "refs/heads/main" }]
    }
    let may = |role: &str, owner: Option<&str>, u: &[crate::hosted::Update]| crate::hosted::may_push(role, owner, "acme/gadget", u);
    // Any other branch, as an agent likes.
    let zero = "0000000000000000000000000000000000000000";
    assert!(may("agent", None, &[crate::hosted::Update { old: zero, new: &beside, refname: "refs/heads/session/s1" }]).is_ok());
    // Main: not without a landing, not to a head without a pass, never backwards.
    assert!(may("agent", None, &to(&old, &on_top)).unwrap_err().contains("landing"));
    assert!(land("s1"));
    assert!(may("agent", Some("s2"), &to(&old, &on_top)).unwrap_err().contains("does not hold the turn"));
    assert!(may("agent", Some("s1"), &to(&old, &on_top)).unwrap_err().contains("no gate pass"));
    crate::deploy::record_verified(&on_top, "test", &json!({"node": "cpu-1"})).unwrap();
    assert!(may("agent", Some("s1"), &to(&old, &on_top)).is_ok(), "the landing, forward, gated");
    crate::deploy::record_verified(&beside, "test", &json!({"node": "cpu-1"})).unwrap();
    assert!(may("agent", Some("s1"), &to(&old, &beside)).unwrap_err().contains("only forward"));
    assert!(may("agent", Some("s1"), &to(&old, zero)).unwrap_err().contains("never deleted"));
    // The person may do anything; a node's key nothing.
    assert!(may("person", None, &to(&old, &beside)).is_ok());
    assert!(may("node", None, &to(&old, &on_top)).is_err());
}

#[test]
fn only_the_person_makes_a_project_public_and_keys_become_git_only_logins() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-set");
    new_project("secret", false);
    assert!(!crate::hosted::is_public("acme/secret"));
    let e = crate::hosted::set("acme/secret", &json!({"public": true}), "agent", false).unwrap_err();
    assert!(format!("{e:#}").contains("the person's"), "{e:#}");
    crate::hosted::set("acme/secret", &json!({"gate": "cargo test", "description": "Now described"}), "agent", false).unwrap();
    assert_eq!(crate::conf::hub().project("acme/secret").unwrap()["gate"], "cargo test");
    crate::hosted::set("acme/secret", &json!({"public": true}), "person", true).unwrap();
    assert!(crate::hosted::is_public("acme/secret"));
    crate::hosted::set("acme/secret", &json!({"public": false}), "agent", false).unwrap();
    assert!(!crate::hosted::is_public("acme/secret"), "back to private: anyone may");
    // Keys.
    assert!(crate::hosted::add_key("box", "root", "ssh-ed25519 AAAA x", "t").is_err());
    assert!(crate::hosted::add_key("box", "agent", "not a key", "t").is_err());
    crate::hosted::add_key("box", "agent", "ssh-ed25519 AAAAC3Nz comment here", "t").unwrap();
    let lines = crate::hosted::authorized_lines("/usr/local/bin/midas");
    assert_eq!(lines, "restrict,command=\"/usr/local/bin/midas hub git --key box\" ssh-ed25519 AAAAC3Nz midas-key-box\n");
    assert_eq!(crate::hosted::role_of("box").as_deref(), Some("agent"));
    assert!(crate::hosted::remove_key("box", "t").unwrap());
    assert!(crate::hosted::authorized_lines("x").is_empty());
}

#[test]
fn a_public_repository_has_pages_and_a_private_one_none() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-view");
    new_project("open", true);
    use crate::codeview::Page;
    let page = |tail: &str, q: &str| crate::codeview::page("acme/open.git", "midas.example", tail, q).unwrap();
    let html = |tail: &str| match page(tail, "") {
        Some(Page::Html(h)) => h,
        _ => panic!("no page at {tail:?}"),
    };
    let home = html("");
    assert!(home.contains("README.md") && home.contains("A test project") && home.contains("git clone https://midas.example/acme/open.git"));
    assert!(home.contains("href=\"/acme/open/archive/main.tar.gz\""), "a download of main: {home}");
    assert!(home.contains("href=\"/acme/open/log\""), "links at the root, as Forgejo had them: {home}");
    assert!(html("log").contains("Start open"));
    assert!(page("nowhere", "").is_none());
    assert!(home.contains("<article class=\"md\"><h1>open</h1>") && !home.contains("<pre># open"), "the README as a page: {home}");
    assert!(home.contains("class=\"ico\""), "an icon by each file: {home}");
    let file = html("tree/README.md");
    assert!(file.contains("<h1>open</h1>"), "{file}");
    assert!(matches!(page("raw/README.md", ""), Some(Page::Raw(b)) if b.starts_with(b"# open")));
    // Forgejo's paths, sent to ours.
    for (old, new) in [("src/branch/main/README.md", "/acme/open/tree/README.md?rev=main"),
                       ("src/branch/main", "/acme/open/tree?rev=main"),
                       ("raw/commit/abc123/a/b.rs", "/acme/open/raw/a/b.rs?rev=abc123"),
                       ("media/branch/main/x.png", "/acme/open/raw/x.png?rev=main"),
                       ("commits/branch/main", "/acme/open/log?rev=main")] {
        assert!(matches!(page(old, ""), Some(Page::Moved(ref to)) if to == new), "{old}");
    }
    // The front page lists the public one, not the private one.
    new_project("shut", false);
    let front = crate::codeview::front("garage44.example");
    assert!(front.contains("href=\"/acme/open\"") && !front.contains("acme/shut") && front.contains("/login"), "{front}");
}

#[test]
fn a_manifest_names_the_projects_it_uses_and_the_commit_it_pins() {
    let known: std::collections::BTreeSet<String> = ["acme/lib", "acme/app"].map(String::from).into();
    let cargo = "[dependencies]\nlib = { git = \"https://code.example/acme/lib.git\", rev = \"c76404c7\", optional = true }\n\
                 lib_style = { git = \"https://code.example/acme/lib.git\", rev = \"c76404c7\" }\n\
                 other = { git = \"https://github.com/acme/other.git\" }\nrepository = \"https://code.example/acme/app\"\n";
    let u = crate::graph::uses(cargo, "Cargo.toml", &known);
    assert_eq!(u, vec![crate::graph::Use { from: "acme/lib".into(), rev: Some("c76404c7".into()), file: "Cargo.toml".into() }], "one pin, once");
    let pkg = "{\"dependencies\": {\"@acme/lib\": \"https://code.example/acme/lib/archive/5ef10eb3.tar.gz\"}}";
    assert_eq!(crate::graph::uses(pkg, "web/package.json", &known)[0].rev.as_deref(), Some("5ef10eb3"));
    assert!(crate::graph::uses("lib = { git = \"https://code.example/acme/lib.git\", branch = \"main\" }", "Cargo.toml", &known)[0].rev.is_none());
}

#[test]
fn the_map_puts_a_project_one_column_past_what_it_uses_and_the_loners_apart() {
    let names: Vec<String> = ["a/ui", "a/lang", "a/editor", "a/os", "a/web", "a/alone"].map(String::from).into();
    let code: Vec<(String, String)> = [("a/ui", "a/os"), ("a/ui", "a/editor"), ("a/lang", "a/os"), ("a/editor", "a/os"), ("a/ui", "a/web")]
        .map(|(a, b)| (a.to_string(), b.to_string())).into();
    let at = crate::graph::layout(&names, &code, &Default::default());
    let col = |n: &str| at[n].0;
    assert_eq!((col("a/ui"), col("a/lang"), col("a/editor"), col("a/web"), col("a/os")), (0, 0, 1, 1, 2));
    assert_eq!(col("a/alone"), 3, "no code shared: a column of its own");
    // Many such wrap into columns no taller than three, rather than one long one.
    let more: Vec<String> = names.iter().cloned().chain(["a/b", "a/c", "a/d"].map(String::from)).collect();
    let wrapped = crate::graph::layout(&more, &code, &Default::default());
    assert_eq!(wrapped.values().filter(|(c, _)| *c == 3).count(), 3);
    assert_eq!(wrapped.values().filter(|(c, _)| *c == 4).count(), 1);
    // A cycle ends, wherever it puts them.
    let ring: Vec<(String, String)> = [("a/ui", "a/os"), ("a/os", "a/ui")].map(|(a, b)| (a.to_string(), b.to_string())).into();
    assert_eq!(crate::graph::layout(&names, &ring, &Default::default()).len(), names.len());
}

#[test]
fn the_public_map_has_public_projects_only_and_no_sessions() {
    let g = serde_json::json!({
        "projects": [{"name": "a/os", "public": true, "sessions": 40, "techs": 10, "built": 4, "col": 1, "row": 0},
                     {"name": "a/ui", "public": true, "sessions": 9, "techs": 2, "built": 2, "col": 0, "row": 0},
                     {"name": "a/site", "public": false, "sessions": 4, "techs": 3, "built": 1, "col": 2, "row": 0}],
        "code": [{"from": "a/ui", "to": "a/os", "behind": 30}, {"from": "a/os", "to": "a/site", "behind": 0}],
        "shared": [{"a": "a/os", "b": "a/ui", "n": 7}],
        "needs": [{"from": "a/os", "to": "a/site", "n": 3}],
        "landed": [{"name": "Secret page", "repo": "a/site", "at": 2}, {"name": "Boot", "repo": "a/os", "at": 1}],
    });
    let p = crate::graph::public(&g);
    let text = p.to_string();
    assert!(!text.contains("a/site") && !text.contains("Secret") && !text.contains("\"sessions\""), "{text}");
    assert_eq!(p["code"].as_array().unwrap().len(), 1);
    let svg = crate::graph::svg(&p, Some("/"));
    assert!(svg.contains("href=\"/a/os\"") && svg.contains("30 behind") && svg.contains("#c79a3c"), "a stale pin is amber: {svg}");
    assert!(!crate::graph::svg(&g, None).contains("href="), "the page's map carries data-project, not links");
}

#[test]
fn a_forgejo_project_is_imported_with_its_branches_and_its_landing_but_not_its_deploys() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-import");
    struct Conf;
    impl Drop for Conf {
        fn drop(&mut self) {
            // SAFETY: tests hold SERIAL.
            unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
        }
    }
    // "Forgejo": a directory of bare repositories, which git fetches as it would the ssh URL.
    let forge = crate::registry::root().join("forge");
    let old = forge.join("acme/old.git");
    let sh = |dir: &std::path::Path, c: &str| assert!(std::process::Command::new("sh").arg("-c").arg(c).current_dir(dir).status().unwrap().success(), "{c}");
    std::fs::create_dir_all(&old).unwrap();
    sh(&old, "git init -q --bare -b main . && blob=$(echo hello | git hash-object -w --stdin) \
              && tree=$(printf '100644 blob %s\\tREADME\\n' $blob | git mktree) \
              && c=$(git -c user.name=t -c user.email=t@t commit-tree $tree -m first) \
              && git update-ref refs/heads/main $c && git update-ref refs/heads/session/s1 $c && git tag v1 $c");
    // The LFS objects a repository names, on a branch's tree: an import takes each from Forgejo.
    let art = forge.join("acme/art.git");
    std::fs::create_dir_all(&art).unwrap();
    sh(&art, "git init -q --bare -b main . && blob=$(echo hello | git hash-object -w --stdin) \
              && lfs=$(printf 'version https://git-lfs.github.com/spec/v1\\noid sha256:%s\\nsize 5\\n' $(printf %064d 7) | git hash-object -w --stdin) \
              && tree=$(printf '100644 blob %s\\tREADME\\n100644 blob %s\\tpic.png\\n' $blob $lfs | git mktree) \
              && c=$(git -c user.name=t -c user.email=t@t commit-tree $tree -m first) && git update-ref refs/heads/side $c");
    assert_eq!(crate::hosted::lfs_pointers(&art).unwrap(), vec![(format!("{:064}", 7), 5)]);
    let conf = crate::registry::root().join("hub.conf");
    std::fs::write(&conf, json!({"listen": "127.0.0.1:1", "forgejo_ssh": forge.to_string_lossy(), "forgejo_api": "",
        "repos": ["acme/old"], "projects": {"acme/old": {"gate": "make test", "pre_land": "true"}}}).to_string()).unwrap();
    // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
    unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
    let _conf = Conf;
    let forgejo = crate::hosted::Source::default();
    assert!(crate::hosted::import("acme/nope", true, "", &forgejo, "t").is_err(), "nothing to fetch");
    assert!(!crate::hosted::path("acme/nope").exists(), "a failed import leaves nothing");
    let v = crate::hosted::import("acme/old", true, "An old project", &forgejo, "t").unwrap();
    assert_eq!(v["branches"], 2);
    assert_eq!(v["lfs_objects"], 0);
    assert!(crate::hosted::is_public("acme/old"));
    let dir = crate::hosted::path("acme/old");
    sh(&dir, "git rev-parse -q --verify refs/tags/v1 >/dev/null && test -x hooks/pre-receive");
    let p = crate::conf::hub().project("acme/old").unwrap();
    assert_eq!(p["gate"], "make test");
    assert!(crate::hosted::get("acme/old").unwrap()["project"].get("deploy").is_none());
    assert!(crate::hosted::import("acme/old", true, "", &forgejo, "t").is_err(), "not twice");
    // One hub.conf does not name, from a path, with an LFS object nowhere to be had: no landing, and the object named.
    let empty = crate::registry::root().join("no-lfs");
    std::fs::create_dir_all(&empty).unwrap();
    let v = crate::hosted::import("acme/art", false, "", &crate::hosted::Source { git: Some(&art.to_string_lossy()), lfs: Some(&empty) }, "t").unwrap();
    assert_eq!(v["lfs_missing"], json!([format!("{:064}", 7)]));
    assert!(!crate::hosted::is_public("acme/art") && crate::conf::hub().project("acme/art").unwrap()["gate"].is_null());
}

#[test]
fn forgejo_calls_about_a_hosted_repository_are_answered_by_the_hub() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-forgejo");
    new_project("here", false);
    let (code, v) = crate::hub::forgejo_for_hosted("GET", "/repos/acme/here/branches?limit=50").unwrap();
    assert_eq!(code, 200);
    assert_eq!(v[0]["name"], "main");
    assert_eq!(v[0]["commit"]["id"].as_str().unwrap().len(), 40);
    let (code, v) = crate::hub::forgejo_for_hosted("POST", "/repos/acme/here/pulls").unwrap();
    assert_eq!(code, 410);
    assert!(v["message"].as_str().unwrap().contains("project_read"));
    assert!(crate::hub::forgejo_for_hosted("GET", "/repos/acme/elsewhere/branches").is_none(), "Forgejo's own");
    assert!(crate::hub::forgejo_for_hosted("GET", "/version").is_none());
}

#[test]
fn a_nodes_readings_are_kept_and_bucketed_over_time() {
    let _g = SERIAL.lock().unwrap();
    scratch("usage");
    let gib = 1u64 << 30;
    let t = registry::now() - 3 * 60;
    // Three minutes: a link peaks between two readings in the second; the
    // third, from a node too old to sample peaks, counts its own value; the
    // cgroup's OOM count rises once.
    for (i, (mem, peak, load, oom)) in [(4 * gib, Some(5 * gib), 2.0, 1), (6 * gib, Some(18 * gib), 9.0, 1), (3 * gib, None, 1.0, 2)].into_iter().enumerate() {
        let mut r = json!({"at": t + i as i64 * 60, "mem_anon": mem, "mem_max": 24 * gib, "load": load, "cpus": 6,
                           "disk_free": 50_000_000_000u64 - i as u64 * 1_000_000_000, "disk_total": 200_000_000_000u64,
                           "target_bytes": 30_000_000_000u64, "sessions": (i == 1) as u64, "oom_kills": oom});
        if let Some(p) = peak {
            r["mem_peak"] = json!(p);
        }
        crate::usage::record("mac-1", &r).unwrap();
    }
    crate::usage::record("mac-2", &json!({"at": t, "mem_anon": gib, "load": 0.5, "cpus": 6})).unwrap();
    let u = crate::usage::read(3600, Some(3600));
    let w = &u["nodes"]["mac-1"]["whole"];
    assert_eq!(w["minutes"], 3);
    assert_eq!(w["mem_peak"].as_f64(), Some((18 * gib) as f64), "the peak between readings, not the readings");
    assert_eq!(w["mem_lim"].as_f64(), Some((24 * gib) as f64));
    assert_eq!(w["load_max"].as_f64(), Some(9.0));
    assert_eq!(w["over_cpus"].as_f64(), Some(0.333), "one minute in three past 6 CPUs");
    assert_eq!(w["busy"].as_f64(), Some(0.333));
    assert_eq!(w["disk_free_min"].as_f64(), Some(48e9));
    assert_eq!(w["oom_kills"], 1, "kills that happened in the window, not since the cgroup started");
    assert!(!u["nodes"]["mac-1"]["buckets"].as_array().unwrap().is_empty());
    assert_eq!(u["nodes"]["mac-2"]["whole"]["minutes"], 1, "each node on its own");
    // Lines past the window are not read.
    assert!(crate::usage::read(30, None)["nodes"].as_object().unwrap().is_empty());
}

#[test]
fn a_session_started_from_a_session_remembers_it() {
    use crate::sessions;
    let _g = SERIAL.lock().unwrap();
    scratch("started-from");
    let parent = sessions::start("ana", "build the map", None, None, None, None, None, &Value::Null).unwrap();
    let child = sessions::start("agent", "the part apart", None, None, None, None, None, &Value::Null).unwrap();
    sessions::set_from(&child, &parent).unwrap();
    assert_eq!(sessions::meta(&child).unwrap()["from"], parent.as_str());
    // Never itself, nor one that is not there.
    sessions::set_from(&parent, &parent).unwrap();
    sessions::set_from(&parent, "s99999").unwrap();
    assert!(sessions::meta(&parent).unwrap()["from"].is_null());
}

#[test]
fn a_renamed_project_moves_with_its_sessions_and_its_old_name_still_leads_to_it() {
    let _g = SERIAL.lock().unwrap();
    scratch("hosted-rename");
    new_project("flits", false);
    new_project("other", false);
    let state = registry::root();
    let meta = |id: &str, m: Value| {
        std::fs::create_dir_all(state.join("hosted").join(id)).unwrap();
        std::fs::write(state.join("hosted").join(id).join("meta.json"), m.to_string()).unwrap();
    };
    meta("s1", json!({"id": "s1", "repo": "acme/other", "repos": ["acme/other", "acme/flits"], "layout": "folder"}));
    meta("s2", json!({"id": "s2", "repo": "acme/other"}));
    std::fs::create_dir_all(state.join("memory")).unwrap();
    std::fs::write(state.join("memory/acme--flits.json"), "{}").unwrap();

    assert!(crate::hosted::rename("acme/flits", "other", "t").unwrap_err().to_string().contains("a project already"));
    assert!(crate::hosted::rename("acme/flits", "../x", "t").is_err(), "a name does not walk out");
    let v = crate::hosted::rename("acme/flits", "flitz", "agent:s1").unwrap();
    assert_eq!((v["repo"].as_str(), v["sessions"].clone()), (Some("acme/flitz"), json!(["s1"])));
    assert!(crate::hosted::path("acme/flitz").join("HEAD").exists() && !crate::hosted::path("acme/flits").exists());
    assert_eq!(crate::hosted::get("acme/flitz").unwrap()["renamed_from"][0]["name"], "acme/flits");
    assert!(state.join("memory/acme--flitz.json").exists(), "its notes go with it");
    let s1 = crate::sessions::meta("s1").unwrap();
    assert_eq!(s1["repos"], json!(["acme/other", "acme/flitz"]));
    // The old name, from a checkout made before: it leads to the new one.
    assert_eq!(crate::hosted::current("acme/flits.git"), "acme/flitz.git");
    assert_eq!(crate::mirror::mirror_path(&crate::hosted::current("acme/flits.git")), crate::hosted::path("acme/flitz"));
    assert!(crate::conf::hub().allows("acme/flitz.git") && !crate::conf::hub().allows("acme/flits.git"));
    // Renamed again, and back: no chain, no alias of a name in use.
    crate::hosted::rename("acme/flitz", "blitz", "t").unwrap();
    assert_eq!(crate::hosted::current("acme/flits"), "acme/blitz");
    crate::hosted::rename("acme/blitz", "flits", "t").unwrap();
    assert_eq!(crate::hosted::current("acme/flits"), "acme/flits");
    let mut r = crate::hosted::renames();
    r.sort();
    assert_eq!(r, [("acme/blitz".to_string(), "acme/flits".to_string()), ("acme/flitz".to_string(), "acme/flits".to_string())]);

    // Deleting is the person's; it goes aside, out of every list.
    assert!(crate::hosted::delete("acme/flits", "agent:s1", false).unwrap_err().to_string().contains("the person's"));
    let d = crate::hosted::delete("acme/flits", "web:person", true).unwrap();
    let kept = std::path::PathBuf::from(d["kept"].as_str().unwrap());
    assert!(kept.join("HEAD").exists() && !crate::hosted::path("acme/flits").exists(), "moved aside, not lost");
    assert!(!crate::hosted::is_hosted("acme/flits") && !crate::conf::hub().allows("acme/flits.git"));
    assert!(crate::hosted::renames().is_empty(), "no old name leads to a deleted one");
    let s1 = crate::sessions::meta("s1").unwrap();
    assert_eq!((s1["repos"].clone(), s1["repo"].as_str()), (json!(["acme/other"]), Some("acme/other")));
    assert!(crate::hosted::delete("acme/flits", "web:person", true).is_err(), "once");
    // Its name is free for a new project.
    new_project("flits", false);
}

#[test]
fn a_runner_moves_its_checkout_of_a_renamed_project_and_its_worktrees_follow() {
    let home = std::env::temp_dir().join(format!("midas-test-follow-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&home);
    let old = home.join("repos/acme/flits");
    std::fs::create_dir_all(&old).unwrap();
    let git = |dir: &std::path::Path, args: &[&str]| {
        let out = std::process::Command::new("git").arg("-C").arg(dir).args(args)
            .env("GIT_AUTHOR_NAME", "t").env("GIT_AUTHOR_EMAIL", "t@t").env("GIT_COMMITTER_NAME", "t").env("GIT_COMMITTER_EMAIL", "t@t")
            .output().unwrap();
        assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };
    git(&old, &["init", "-q", "-b", "main"]);
    git(&old, &["commit", "-q", "--allow-empty", "-m", "Start flits"]);
    git(&old, &["remote", "add", "origin", "midas@10.44.0.1:acme/flits.git"]);
    let work = home.join("session-s1/flits");
    git(&old, &["worktree", "add", "-q", "-b", "session/s1", &work.to_string_lossy()]);
    let renamed = json!([{"from": "acme/flits", "to": "acme/flitz", "git": "midas@10.44.0.1:acme/flitz.git"}]);
    crate::sessions::follow_renames(&home, &renamed);
    let new = home.join("repos/acme/flitz");
    assert!(new.join(".git").exists() && !old.exists());
    assert_eq!(git(&new, &["remote", "get-url", "origin"]), "midas@10.44.0.1:acme/flitz.git");
    // The session's worktree, in its folder as it was, finds its checkout and says the new name.
    assert_eq!(git(&work, &["rev-parse", "--abbrev-ref", "HEAD"]), "session/s1");
    assert_eq!(crate::cli::repo_in(&work).as_deref(), Some("acme/flitz"));
    assert_eq!(crate::sessions::folder_projects(&home.join("session-s1")), ["acme/flitz"]);
    crate::sessions::follow_renames(&home, &renamed);
    assert!(new.join(".git").exists(), "once");
    let _ = std::fs::remove_dir_all(&home);
}