garage44.eu/jeroen/midas

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

.. /src/cli.rs

raw

//! The commands people and agents type. All of them ask the hub (`client`);
//! nothing here touches the workspace's state directly.
//!
//! Who "I" am is the worktree the command runs in — one per agent session —
//! unless `--owner` (on any command) or MIDAS_OWNER says otherwise: the
//! landing gate claims as `gate-<worktree>`.

use std::process::Command;
use std::time::{Duration, Instant};

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

use crate::client;
use crate::events;
use crate::registry::{self, now, Mode};

/// The worktree this runs in, by name.
pub fn owner() -> String {
    if let Ok(o) = std::env::var("MIDAS_OWNER") {
        return o;
    }
    Command::new("git").args(["rev-parse", "--show-toplevel"]).output().ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .or_else(|| std::env::current_dir().ok().map(|d| d.to_string_lossy().to_string()))
        .map(|p| crate::flush::worktree_owner(std::path::Path::new(&p)))
        .filter(|o| !o.is_empty())
        .unwrap_or_else(|| "?".into())
}

/// The branch this worktree has checked out, or `None` on a detached HEAD
/// (or outside a checkout). `rev-parse --abbrev-ref HEAD` says "HEAD" there,
/// and a node or a landing turn was taken as branch "HEAD".
pub fn branch() -> Option<String> {
    branch_in(std::path::Path::new("."))
}

/// The repository of the checkout at `dir` (`owner/name`, its origin's): its project, when it is one.
pub fn repo_in(dir: &std::path::Path) -> Option<String> {
    crate::flush::repo_of_url(crate::util::git(dir, &["remote", "get-url", "origin"]).ok()?.trim())
}

/// The same, for the checkout at `dir`.
pub fn branch_in(dir: &std::path::Path) -> Option<String> {
    Command::new("git").arg("-C").arg(dir).args(["symbolic-ref", "--quiet", "--short", "HEAD"]).output().ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|b| !b.is_empty())
}

pub struct Take {
    pub owner: String,
    pub machine: String,
    pub node: Option<String>,
    pub purpose: Option<String>,
    pub wait: u64,
    pub mode: Mode,
    /// Of the free nodes, the one fastest at this kind of command.
    pub rank: Option<String>,
    /// Ask for `node` next: its holder is told and keeps it, and when they
    /// let go it comes to this claim instead of the queue (`reserve_next`).
    pub next: bool,
}

/// What came of waiting in line.
pub enum Taken {
    Node(String),
    /// Out of time, with the place in line kept.
    Queued,
}

/// Exit status of a `take` or `wait` that ran out of time but kept its place in
/// line (EX_TEMPFAIL): try `midas wait` within two minutes.
pub const QUEUED: i32 = 75;

/// A wait in line rides out the hub being briefly unreachable — it restarts
/// when it is updated — rather than ending the wait and losing the place: the
/// hub keeps a place for two minutes without asking, so retrying for one keeps
/// it.
#[derive(Default)]
struct Outage {
    since: Option<Instant>,
}

impl Outage {
    const RIDE_OUT: Duration = Duration::from_secs(60);

    /// The answer, or `None` after a pause when the hub did not answer and the
    /// outage is still short.
    fn ask<T>(&mut self, f: impl FnOnce() -> Result<T>) -> Result<Option<T>> {
        match f() {
            Ok(v) => {
                self.since = None;
                Ok(Some(v))
            }
            Err(e) => {
                let since = *self.since.get_or_insert_with(Instant::now);
                if since.elapsed() > Self::RIDE_OUT {
                    return Err(e);
                }
                std::thread::sleep(Duration::from_secs(5));
                Ok(None)
            }
        }
    }
}

/// Wait in line for a node, take it, and bring it to this worktree. Prints the
/// node's name on stdout (`node=$(midas take)`); everything else on stderr.
pub fn take(t: &Take) -> Result<i32> {
    match take_node(t)? {
        Taken::Node(id) => {
            eprintln!("run there:  ssh {id} 'cargo test …'   ·   give it back: midas release");
            println!("{id}");
            Ok(0)
        }
        Taken::Queued => Ok(QUEUED),
    }
}

/// How long a take waits while every node it could have is offline or drained.
const DEAD_WAIT: Duration = Duration::from_secs(15 * 60);

/// `take` without its answer on stdout: the node's name is returned, and
/// everything said along the way goes to stderr (`midas bot start` builds on it).
pub fn take_node(t: &Take) -> Result<Taken> {
    // A Claude Code subagent's own worktree: no session hook runs for it, so
    // nothing would give the node back but the 30-minute idle release.
    let top = Command::new("git").args(["rev-parse", "--show-toplevel"]).output().ok()
        .filter(|o| o.status.success()).map(|o| std::path::PathBuf::from(String::from_utf8_lossy(&o.stdout).trim()));
    if let Some(top) = top.filter(|p| crate::collab::subagent_worktree(p) && p.file_name().is_some_and(|n| *n == *t.owner)) {
        bail!("this is a Claude Code subagent's own worktree ({}): no session hook runs for it, so a node taken \
               here would stay held until it sat idle for 30 minutes, and the node of the session that started \
               you does not follow this worktree. Give the build back to that session: it runs `ssh <node> …` \
               from its own worktree.", top.display());
    }
    let branch = branch();
    let quiet = t.mode == Mode::Job;
    let body = json!({
        "owner": t.owner, "machine": t.machine, "node": t.node, "purpose": t.purpose,
        "branch": branch, "queue": true, "mode": t.mode.as_str(), "rank": t.rank,
    });
    if t.next {
        let Some(node) = &t.node else { bail!("--next is for one node: name it with --node") };
        let v = client::post("/v1/next", &json!({"owner": t.owner, "node": node,
            "why": t.purpose.clone().unwrap_or_else(|| "needs it next".into())}))?;
        match v["holder"].as_str() {
            Some(h) => eprintln!("{node} is yours next: {h} has been told, and keeps it until they release it"),
            None => eprintln!("{node} is yours next"),
        }
    }
    let deadline = Instant::now() + Duration::from_secs(t.wait);
    let mut asked = 0u32;
    let mut outage = Outage::default();
    let mut dead_since: Option<Instant> = None;
    let node = loop {
        let Some((code, v)) = outage.ask(|| client::post_raw("/v1/claim", &body))? else { continue };
        if code == 200 {
            break v;
        }
        if code != 409 {
            bail!("{}", v["error"].as_str().unwrap_or("the hub would not answer the claim"));
        }
        let why: Vec<String> = v["passed_over"].as_array().into_iter().flatten()
            .map(|p| format!("{} {}", p["node"].as_str().unwrap_or("?"), p["why"].as_str().unwrap_or("?"))).collect();
        // Nothing passed over is nothing that matches: no node will ever free
        // for it, so say so now rather than at the deadline — a run's is 30 days.
        if why.is_empty() {
            let _ = client::post("/v1/unqueue", &json!({"owner": t.owner}));
            bail!("no node matches {:?}. `midas status` lists them.", t.node.as_deref().unwrap_or(&t.machine));
        }
        // Every node that matches offline or drained: none frees by being given
        // back. A drain for an update lasts minutes, so give it [`DEAD_WAIT`];
        // a session waited 9.5 h from 2026-11-23 for a GPU while the Macs were
        // drained and the deck was off.
        let dead = v["passed_over"].as_array().into_iter().flatten()
            .all(|p| matches!(p["why"].as_str(), Some("offline" | "drained")));
        if !dead {
            dead_since = None;
        } else if dead_since.get_or_insert_with(Instant::now).elapsed() >= DEAD_WAIT {
            let _ = client::post("/v1/unqueue", &json!({"owner": t.owner}));
            bail!("every node that matches {:?} has been offline or drained for {} minutes ({}): none will come free \
                   by waiting. Ask for another kind (`midas take any`), or `midas check` for why they are out.",
                t.node.as_deref().unwrap_or(&t.machine), DEAD_WAIT.as_secs() / 60, why.join(", "));
        }
        if Instant::now() >= deadline {
            // Out of time, but still in line: whoever runs `midas wait` next
            // (in the background, for an agent) keeps the place.
            eprintln!("no node free yet ({}); you are still in line — {}.\n\
                       Keep your place {} within two minutes (run it in the background).",
                why.join(", "), v["position"].as_str().unwrap_or("waiting"),
                if t.mode == Mode::Bot { "by running the same `midas bot start` again" } else { "with `midas wait`" });
            return Ok(Taken::Queued);
        }
        // Where we stand, now and every two minutes.
        if asked % 24 == 0 {
            eprintln!("waiting: {}", v["position"].as_str().unwrap_or("in line"));
        }
        asked += 1;
        std::thread::sleep(Duration::from_secs(5));
    };
    let id = node["id"].as_str().unwrap_or("?").to_string();
    if let Some(named) = t.node.as_deref().filter(|n| *n != id) {
        eprintln!("took {id} instead of {named}: {named} was not free for {} minutes, and {id} is on its machine",
            registry::NAMED_FALLBACK_S / 60);
    }
    if quiet {
        // A run's own ssh brings the node to this worktree.
        return Ok(Taken::Node(id));
    }
    eprintln!("took {id}");
    // One ssh brings the node to this worktree (the flush runs before it) and
    // proves it got there.
    if let Ok(o) = Command::new("git").args(["rev-parse", "HEAD"]).output() {
        let head = String::from_utf8_lossy(&o.stdout).trim().to_string();
        if !head.is_empty() {
            let got = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id, "git rev-parse HEAD"]).output()
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default();
            if got == head {
                eprintln!("{id} follows this worktree ({}): every ssh to it sends your latest edits first", crate::util::sha8(&head));
            } else {
                eprintln!("midas: {id} is at {} after its flush, not {head} — `midas log --node {id}` says why",
                    if got.is_empty() { "nothing" } else { &got });
            }
        }
    }
    Ok(Taken::Node(id))
}

/// `midas run [machine] -- <command>`: a node for one command. Waits in line
/// for as long as it takes (an agent runs it in the background), takes the
/// node fastest at this command — the one this session ran on last, when it
/// ties — runs the command there over ssh (which sends the worktree first),
/// and exits with its status. The lease is a job lease: it goes back a
/// minute after the command when somebody waits, ten when nobody does, so a
/// session reading and editing between two builds holds no node. A node held
/// already, in any mode, is used as it is.
pub fn run(owner: &str, machine: &str, node: Option<String>, purpose: Option<String>, command: &[String]) -> Result<i32> {
    let line = command.join(" ");
    let id = match held(owner)?.and_then(|n| n["id"].as_str().map(str::to_string)) {
        Some(id) => id,
        None => {
            let t = Take {
                owner: owner.to_string(), machine: machine.to_string(), node, purpose: purpose.or_else(|| Some(line.clone())),
                wait: 30 * 86400, mode: Mode::Job, rank: Some(line.clone()), next: false,
            };
            match take_node(&t)? {
                Taken::Node(id) => id,
                Taken::Queued => unreachable!("a run waits for as long as it takes"),
            }
        }
    };
    eprintln!("midas run: on {id}");
    // One shell line. Several words are quoted one by one: ssh joins its
    // arguments with spaces and the node's shell splits them again, so `midas
    // run -- bash -c 'a; b'` reached the node as `bash -c a; b` (2026-11-21).
    // One word is a shell line as given (`midas run -- 'cd web && bun test'`).
    let remote = match command {
        [one] => one.clone(),
        many => many.iter().map(|w| crate::bot::sh_quote(w)).collect::<Vec<_>>().join(" "),
    };
    let st = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id]).arg(remote).status()
        .with_context(|| format!("ssh {id}"))?;
    Ok(st.code().unwrap_or(1))
}

pub fn release(owner: &str, node: Option<&str>, force: bool) -> Result<i32> {
    // A bot goes with its lease. Stopped here when the node answers; its own
    // heartbeat stops it within a minute when it does not.
    if let Ok(st) = client::state() {
        let held = st["leases"].as_object().into_iter().flatten().find(|(sid, l)| {
            (l["owner"] == owner && node.is_none_or(|n| n == sid.as_str())) || (force && node == Some(sid.as_str()))
        });
        if let Some((sid, _)) = held.filter(|(_, l)| registry::mode_of(l) == Mode::Bot) {
            crate::bot::stop_remote(sid);
        }
    }
    let (code, v) = client::post_raw("/v1/release", &json!({"owner": owner, "node": node, "force": force}))?;
    if code == 200 {
        println!("released {}", v["node"].as_str().unwrap_or("?"));
        Ok(0)
    } else {
        eprintln!("{}", v["error"].as_str().unwrap_or("nothing to release"));
        Ok(1)
    }
}

pub fn renew(owner: &str, command: Option<&str>) -> Result<i32> {
    let (code, v) = client::post_raw("/v1/renew", &json!({"owner": owner, "command": command}))?;
    if code == 200 { println!("{}", v["node"].as_str().unwrap_or("?")); Ok(0) } else { Ok(1) }
}

/// The node `owner` holds, with its lease, owner and mode beside it.
pub fn held(owner: &str) -> Result<Option<Value>> {
    let st = client::state()?;
    let Some((sid, lease)) = st["leases"].as_object().into_iter().flatten().find(|(_, l)| l["owner"] == owner) else {
        return Ok(None);
    };
    let mut node = st["nodes"].as_array().into_iter().flatten().find(|s| s["id"] == sid.as_str()).cloned().unwrap_or_default();
    node["lease"] = lease.clone();
    node["owner"] = json!(owner);
    node["mode"] = json!(registry::mode_of(lease).as_str());
    Ok(Some(node))
}

/// `midas mine`: the node `owner` holds, as JSON; exit 1 if none.
pub fn mine(owner: &str) -> Result<i32> {
    match held(owner)? {
        Some(node) => {
            println!("{node}");
            Ok(0)
        }
        None => Ok(1),
    }
}

/// Carry on waiting for the node a `take` asked for, keeping its place in line.
pub fn wait(owner: &str, timeout: u64) -> Result<i32> {
    let st = client::state()?;
    if st["leases"].as_object().into_iter().flatten().any(|(_, l)| l["owner"] == owner) {
        return mine(owner);
    }
    let Some(w) = st["waiters"].get(owner).cloned() else {
        bail!("{owner} is not waiting for a node (a place in line lasts two minutes without asking) — `midas take` again");
    };
    take(&Take {
        owner: owner.to_string(),
        machine: w["machine"].as_str().unwrap_or("any").to_string(),
        node: w["node"].as_str().map(str::to_string),
        purpose: w["purpose"].as_str().map(str::to_string),
        wait: timeout,
        mode: Mode::parse(w["mode"].as_str()).unwrap_or(Mode::Build),
        rank: w["rank"].as_str().map(str::to_string),
        next: false,
    })
}

pub fn drain(node: &str, why: Option<&str>, by: &str) -> Result<i32> {
    client::post("/v1/drain", &json!({"node": node, "why": why, "owner": by}))?;
    match why {
        Some(w) => println!("{node} drained: {w}"),
        None => println!("{node} back in the pool"),
    }
    Ok(0)
}

pub fn ago(ts: i64) -> String {
    let s = (now() - ts).max(0);
    if s < 90 { format!("{s}s ago") } else if s < 5400 { format!("{}m ago", s / 60) } else { format!("{:.1}h ago", s as f64 / 3600.0) }
}

fn clock(ts: i64) -> String {
    chrono::Local.timestamp_opt(ts, 0).single().map(|t| t.format("%H:%M").to_string()).unwrap_or_else(|| "?".into())
}

/// Who holds each node, for what, since and until when, doing what; each
/// node's heartbeat; the queue; and what happened lately.
pub fn status(json_out: bool, recent: Option<usize>, owner: &str) -> Result<i32> {
    let st = client::state()?;
    if json_out {
        println!("{}", serde_json::to_string_pretty(&st)?);
        return Ok(0);
    }
    let history = client::events(&events::Filter { since: chrono::Duration::hours(24), kinds: vec![], node: None, actor: None })
        .unwrap_or_default();
    for s in st["nodes"].as_array().into_iter().flatten() {
        let id = s["id"].as_str().unwrap_or("?");
        let head = format!("{id} ({}, {})", s["machine"].as_str().unwrap_or("?"), s["renderer"].as_str().unwrap_or("?"));
        let lease = st["leases"].get(id);
        if let Some(d) = s["drained"].as_object() {
            println!("{head}: DRAINED — {} (by {}, {}) · `midas nodes undrain {id}` puts it back",
                d.get("why").and_then(Value::as_str).unwrap_or("?"), d.get("by").and_then(Value::as_str).unwrap_or("?"),
                ago(d.get("at").and_then(Value::as_i64).unwrap_or(0)));
        } else if let Some(since) = s["asleep"]["since"].as_i64() {
            println!("{head}: asleep — its VM was shut down {} because nobody used it; it starts when somebody waits for a node (a minute or two)", ago(since));
        } else if s["enabled"] != true {
            println!("{head}: out of the pool — no heartbeat (asleep or down); it rejoins when it reports");
        }
        if let Some(l) = lease {
            println!("{head}: {}", holding(l));
            let branch = l["branch"].as_str().filter(|b| !b.is_empty()).map(|b| format!(" · branch {b}")).unwrap_or_default();
            let claimed = l["claimed_at"].as_i64().unwrap_or(0);
            let reading = s.get("reading").filter(|r| !r.is_null());
            println!("    since {} ({}) · {}{branch}", clock(claimed), ago(claimed), lease_end(l, reading));
            match (l["last_active"].as_i64(), l["last_command"].as_str()) {
                (Some(t), Some(c)) => println!("    last ran {}: {}", ago(t), crate::util::clip_words(c, 90)),
                _ => println!("    nothing run since it was taken"),
            }
        } else if s["enabled"] == true && !s["drained"].is_object() {
            println!("{head}: free");
        }
        if let Some(r) = s.get("reading").filter(|r| !r.is_null()) {
            println!("    node: {}", registry::describe_reading(r));
        }
        // What went wrong lately, or with --recent N, the last N of everything
        // but the routine (sessions, flushes, warm steps that passed).
        let notable: Vec<&Value> = history.iter().filter(|e| {
            e["node"] == id && match recent {
                None => is_failure(e),
                Some(_) => !matches!(e["kind"].as_str(), Some("ssh_session" | "activity" | "barrier" | "mcp_call" | "git_serve")),
            }
        }).collect();
        let n = recent.unwrap_or(3);
        if n > 0 && !notable.is_empty() {
            println!("    {}:", if recent.is_some() { "recent" } else { "failed lately" });
            for e in &notable[notable.len().saturating_sub(n)..] {
                println!("      {}", crate::util::clip_words(&events::render(e), 160));
            }
        }
    }
    let waiters = st["waiters"].as_object().cloned().unwrap_or_default();
    if !waiters.is_empty() {
        let mut w: Vec<(&String, &Value)> = waiters.iter().collect();
        w.sort_by_key(|(_, v)| v["since"].as_i64().unwrap_or(0));
        println!("queue (first in line first):");
        for (o, v) in w {
            let want = v["node"].as_str().map(str::to_string).unwrap_or_else(|| v["machine"].as_str().unwrap_or("any").to_string());
            println!("    {o} — for {want}, waiting since {} ({})", clock(v["since"].as_i64().unwrap_or(0)), ago(v["since"].as_i64().unwrap_or(0)));
        }
        // Where this session stands, as `midas position` said it.
        if waiters.contains_key(owner) {
            if let Ok(p) = client::get(&format!("/v1/position?owner={owner}")) {
                println!("    you: {}", p.as_str().unwrap_or("?"));
            }
        }
    }
    print_landing(&st["landing"]);
    Ok(0)
}

/// When a lease ends, in words. Not its two-hour TTL: the 30-minute idle rule
/// ends nearly every lease first (29 in a day, 2026-10-21), so "lease until
/// 20:35" misled. A lease with a session open is in use and renewed by it.
pub fn lease_end(lease: &Value, reading: Option<&Value>) -> String {
    let idle_min = registry::IDLE_S / 60;
    let sessions = reading.and_then(|r| r["sessions"].as_u64());
    let bot_up = reading.is_some_and(|r| r["bot"]["running"] == true);
    match (sessions, registry::mode_of(lease)) {
        (Some(n), _) if n > 0 => format!("in use: {n} ssh session{} open", if n == 1 { "" } else { "s" }),
        (Some(_), Mode::Bot) => {
            let contact = lease["last_active"].as_i64().max(lease["contact_at"].as_i64()).unwrap_or(0);
            format!("{}given back after {idle_min} min without word from its holder (last {})",
                if bot_up { "bot running; " } else { "" }, ago(contact))
        }
        (Some(_), Mode::Build) => format!("given back after {idle_min} min with no ssh session (last {})",
            ago(lease["renewed_at"].as_i64().unwrap_or(0))),
        (Some(_), Mode::Job) => format!("a run's: given back a minute after it when somebody waits, {} min when nobody does (ended {})",
            registry::JOB_IDLE_S / 60, ago(lease["renewed_at"].as_i64().unwrap_or(0))),
        // A node that does not report its sessions: only the TTL applies.
        (None, _) => {
            let until = lease["renewed_at"].as_i64().unwrap_or(0) + lease["ttl"].as_i64().unwrap_or(registry::DEFAULT_TTL);
            format!("given back at {} unless renewed", clock(until))
        }
    }
}

/// An event that says something went wrong, for `status`'s default view.
fn is_failure(e: &Value) -> bool {
    let kind = e["kind"].as_str().unwrap_or("");
    kind.ends_with("_failed") || (e["ok"] == false && e["optional"] != true)
        || matches!(kind, "error" | "oom_kill" | "guard" | "lease_lapsed" | "node_offline" | "ssh_blocked"
                          | "ssh_refused" | "git_refused" | "lfs_refused" | "hub_unreachable")
}

fn print_landing(l: &Value) {
    let h = &l["holder"];
    let mut line: Vec<(&String, &Value)> = l["queue"].as_object().into_iter().flatten().collect();
    if !h.is_object() && line.is_empty() {
        return;
    }
    println!("landing:");
    if h.is_object() {
        let step = h["step"].as_str().map(|s| format!(" — {s}")).unwrap_or_default();
        println!("    {} is landing {}, since {} ({}){step}", h["owner"].as_str().unwrap_or("?"),
            h["branch"].as_str().unwrap_or("a detached HEAD"), clock(h["granted_at"].as_i64().unwrap_or(0)), ago(h["granted_at"].as_i64().unwrap_or(0)));
    }
    line.sort_by_key(|(_, v)| v["since"].as_i64().unwrap_or(0));
    for (o, v) in line {
        println!("    then {o} — {}, waiting since {} ({})", v["branch"].as_str().unwrap_or("a detached HEAD"),
            clock(v["since"].as_i64().unwrap_or(0)), ago(v["since"].as_i64().unwrap_or(0)));
    }
}

/// `midas land take`: wait for the turn to land on the warm branch, in line
/// behind whoever asked first. Exits 0 holding it; QUEUED if the time ran out
/// (the place is given up: a landing that stops asking is not waiting).
pub fn land_take(owner: &str, purpose: Option<&str>, wait: u64) -> Result<i32> {
    let branch = branch();
    let body = json!({"owner": owner, "branch": branch, "purpose": purpose});
    let deadline = Instant::now() + Duration::from_secs(wait);
    let mut asked = 0u32;
    let mut last = String::new();
    let mut outage = Outage::default();
    loop {
        let Some((code, v)) = outage.ask(|| client::post_raw("/v1/land/claim", &body))? else { continue };
        if code == 200 {
            eprintln!("your turn to land — nobody else lands until `midas land release`");
            return Ok(0);
        }
        if code != 409 {
            bail!("{}", v["error"].as_str().unwrap_or("the hub would not answer"));
        }
        let pos = v["position"].as_str().unwrap_or("in line").to_string();
        if Instant::now() >= deadline {
            let _ = client::post("/v1/land/release", &json!({"owner": owner, "outcome": "gave up waiting"}));
            eprintln!("no turn to land within {}m ({pos}); gave the place up", wait / 60);
            return Ok(QUEUED);
        }
        // Where we stand when it changes, and every two minutes.
        if pos != last || asked % 8 == 0 {
            eprintln!("waiting to land: {pos}");
            last = pos;
        }
        asked += 1;
        std::thread::sleep(Duration::from_secs(15));
    }
}

pub fn land_renew(owner: &str, step: Option<&str>) -> Result<i32> {
    let (code, v) = client::post_raw("/v1/land/renew", &json!({"owner": owner, "step": step}))?;
    if code == 200 {
        return Ok(0);
    }
    eprintln!("{}", v["error"].as_str().unwrap_or("could not renew the landing turn"));
    Ok(1)
}

pub fn land_release(owner: &str, outcome: Option<&str>, sha: Option<&str>) -> Result<i32> {
    let (code, v) = client::post_raw("/v1/land/release", &json!({"owner": owner, "outcome": outcome, "sha": sha}))?;
    if code == 200 {
        eprintln!("gave back the landing turn");
        return Ok(0);
    }
    eprintln!("{}", v["error"].as_str().unwrap_or("nothing to give back"));
    Ok(1)
}

/// git in the current checkout, its output trimmed; an error says what failed.
fn git_here(args: &[&str]) -> Result<String> {
    let out = Command::new("git").args(args).output()?;
    if !out.status.success() {
        bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// `midas land targets`: what this branch's landing changes for each target
/// deployed after landings, worked out here, where the commits are; which of
/// them it builds (`ship::pick`); with `record`, told to the hub for HEAD.
pub fn land_targets(base: Option<&str>, pick: Option<&str>, record: bool, as_json: bool, owner: &str) -> Result<i32> {
    let repo = repo_in(std::path::Path::new("."))
        .context("this checkout has no origin that names a repository (owner/name)")?;
    let p = client::get(&format!("/v1/project?repo={repo}"))?;
    let main = p["main"].as_str().unwrap_or("main");
    let head = git_here(&["rev-parse", "HEAD"])?;
    let base = match base {
        Some(b) => git_here(&["rev-parse", b])?,
        None => git_here(&["merge-base", "HEAD", &format!("origin/{main}")])?,
    };
    let changes = |paths: &[Value]| -> Result<bool> {
        let mut args = vec!["diff".to_string(), "--name-only".into(), base.clone(), head.clone(), "--".into()];
        args.extend(paths.iter().filter_map(|p| p.as_str().map(str::to_string)));
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        Ok(!git_here(&args)?.is_empty())
    };
    let mut facts = vec![];
    for t in p["deploy"].as_array().into_iter().flatten().filter(|t| t["after_landing"] == true) {
        let paths = t["paths"].as_array().cloned().unwrap_or_default();
        let required_by = t["required_by"].as_array().cloned().unwrap_or_default();
        facts.push(crate::ship::Facts {
            target: t["target"].as_str().unwrap_or("?").to_string(),
            // Naming nothing it is built from, every landing builds it.
            changed: paths.is_empty() || changes(&paths)?,
            optional: t["optional"] == true,
            required: !required_by.is_empty() && changes(&required_by)?,
        });
    }
    let picked = crate::ship::pick(&facts, pick)?;
    if as_json {
        let each: Vec<Value> = facts.iter().map(|f| json!({"target": f.target, "changed": f.changed, "optional": f.optional,
            "required": f.required, "builds": picked.contains(&f.target)})).collect();
        println!("{}", json!({"repo": repo, "base": base, "head": head, "builds": picked, "targets": each}));
    } else {
        let names = |f: &dyn Fn(&crate::ship::Facts) -> bool| facts.iter().filter(|x| f(x)).map(|x| x.target.as_str()).collect::<Vec<_>>().join(", ");
        let builds: Vec<String> = facts.iter().filter(|f| picked.contains(&f.target))
            .map(|f| if f.required && f.optional { format!("{} (must: it stays in step with what changed)", f.target) } else { f.target.clone() }).collect();
        println!("builds after landing:  {}", if builds.is_empty() { "nothing".into() } else { builds.join(", ") });
        let can = names(&|f| f.changed && !picked.contains(&f.target));
        if !can.is_empty() {
            println!("changed, not built:    {can}  (`--pick +name` builds it; otherwise it goes once no session is at work)");
        }
        let same = names(&|f| !f.changed);
        if !same.is_empty() {
            println!("unchanged:             {same}");
        }
    }
    if record {
        client::post("/v1/land/targets", &json!({"repo": repo, "sha": head, "targets": picked, "asked": pick, "owner": owner}))?;
        if !as_json {
            println!("told the hub: the landing of {} builds {}", &head[..8], if picked.is_empty() { "nothing".into() } else { picked.join(", ") });
        }
    }
    Ok(0)
}

/// `midas project`: this checkout's project as the hub has it, or one of its
/// settings raw (empty when unset), for a script to read.
pub fn project(get: Option<&str>, repo: Option<String>) -> Result<i32> {
    let repo = match repo {
        Some(r) => r,
        None => repo_in(std::path::Path::new("."))
            .context("this checkout has no origin that names a repository (owner/name); --repo says which")?,
    };
    // Sent as it is: the hub reads query values undecoded, so an encoded `/`
    // named no repository at all.
    if !repo.chars().all(|c| c.is_ascii_alphanumeric() || "/-_.".contains(c)) {
        bail!("not a repository name (owner/name): {repo}");
    }
    let p = client::get(&format!("/v1/project?repo={repo}"))?;
    match get {
        None => println!("{}", serde_json::to_string_pretty(&p)?),
        Some(k) => match p.get(k) {
            None => bail!("no setting {k}: {}", p.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>().join(", ")).unwrap_or_default()),
            Some(Value::Null) => println!(),
            Some(Value::String(s)) => println!("{s}"),
            Some(v) => println!("{v}"),
        },
    }
    Ok(0)
}

pub fn land_status() -> Result<i32> {
    let st = client::state()?;
    if !st["landing"]["holder"].is_object() && st["landing"]["queue"].as_object().is_none_or(|q| q.is_empty()) {
        println!("nobody is landing");
    }
    print_landing(&st["landing"]);
    Ok(0)
}

/// Who holds a node and for what, in words: "held by wt — purpose", or for a
/// bot lease "bot, held by wt — purpose", so a bot does not read as a build
/// somebody forgot.
pub fn holding(l: &Value) -> String {
    let purpose = l["purpose"].as_str().map(|p| format!(" — {p}")).unwrap_or_default();
    let what = if registry::mode_of(l) == Mode::Bot { "bot, held by" } else { "held by" };
    format!("{what} {}{purpose}", l["owner"].as_str().unwrap_or("?"))
}

pub fn log(f: &events::Filter, json_out: bool) -> Result<i32> {
    let evs = client::events(f)?;
    for e in &evs {
        println!("{}", if json_out { e.to_string() } else { events::render(e) });
    }
    if evs.is_empty() && !json_out {
        eprintln!("no events");
    }
    Ok(0)
}

/// The story of one node: what concerned it, including refusals that passed it over.
pub fn explain(node: &str, since: chrono::Duration) -> Result<i32> {
    let all = client::events(&events::Filter { since, kinds: vec![], node: None, actor: None })?;
    let mut n = 0;
    for e in all.iter().filter(|e| e["node"] == node || e["wanted"] == node
        || e["passed_over"].as_array().is_some_and(|p| p.iter().any(|x| x["node"] == node))) {
        println!("{}", events::render(e));
        n += 1;
    }
    if n == 0 {
        eprintln!("nothing recorded about {node} in that window");
    }
    Ok(0)
}

/// `midas nodes list`, kept for scripts: one line per node.
pub fn nodes_list() -> Result<i32> {
    for n in client::nodes()? {
        println!("{:<8} machine {:<6} {}:{:<5} {} · {}", n["id"].as_str().unwrap_or("?"), n["machine"].as_str().unwrap_or("?"),
            n["address"].as_str().unwrap_or("?"), n["ssh_port"], n["renderer"].as_str().unwrap_or("?"),
            if n["enabled"] == true { "in the pool" } else { "out of the pool" });
    }
    Ok(0)
}

/// `cargo` is this binary under another name (a symlink where agents work), so
/// a build typed in the wrong place is answered with where to run it.
pub fn as_alias(name: &str, args: &[String]) -> Option<Result<i32>> {
    match name {
        "cargo" => Some(cargo_alias(args)),
        _ => None,
    }
}

fn cargo_alias(args: &[String]) -> Result<i32> {
    let real = ["/usr/local/cargo/bin/cargo", "/root/.cargo/bin/cargo"].iter()
        .map(std::path::PathBuf::from)
        .chain(std::env::var("HOME").ok().map(|h| std::path::Path::new(&h).join(".cargo/bin/cargo")))
        .find(|p| p.exists() && std::fs::canonicalize(p).ok() != std::env::current_exe().ok())
        .context("no real cargo found")?;
    // Everything that compiles runs on a node, project aliases included; what
    // only reads or edits the manifest runs here.
    let builds = !matches!(args.first().map(String::as_str),
        None | Some("fmt" | "metadata" | "tree" | "locate-project" | "pkgid" | "search" | "update" | "generate-lockfile"
                    | "version" | "--version" | "-V" | "help" | "--help" | "-h" | "--list"));
    if builds && std::env::var("MIDAS_LOCAL_BUILD").as_deref() != Ok("1") {
        let held = held(&owner()).ok().flatten();
        let line = args.join(" ");
        match held.as_ref().and_then(|s| s["id"].as_str()) {
            Some(id) => eprintln!("cargo: builds run on your node, not here:\n\n    ssh {id} 'cargo {line}'\n"),
            None => eprintln!("cargo: builds run on a node, not here:\n\n    midas run -- cargo {line}\n\n\
                               It takes a node for this one command, in the background if it may wait, and sends\n\
                               your latest edits first."),
        }
        eprintln!("(MIDAS_LOCAL_BUILD=1 builds here anyway, for a one-off.)");
        return Ok(1);
    }
    use std::os::unix::process::CommandExt;
    Err(Command::new(real).args(args).exec().into())
}

/// `midas deploy [<target>]`: queue a deploy and follow it to the end, or list
/// the targets and the last week's deploys.
/// Hold the deploys that follow landings (`why`), or end the hold (none).
pub fn deploy_hold(why: Option<&str>, owner: &str) -> Result<i32> {
    match why {
        Some(why) => {
            client::post("/v1/deploy/hold", &json!({"why": why, "owner": owner}))?;
            println!("held: what lands goes on main, and nothing is deployed after it until a person deploys or `midas deploy --release`");
        }
        None => {
            let r = client::post("/v1/deploy/release", &json!({"owner": owner}))?;
            println!("{}", if r["released"] == true { "released: the hub deploys what has landed again" } else { "nothing was held" });
        }
    }
    Ok(0)
}

/// `midas deploy --defer <target>`: put off an announced deploy a while (ship.rs `defer`).
pub fn deploy_defer(target: &str, minutes: i64, why: &str, owner: &str) -> Result<i32> {
    let r = client::post("/v1/deploy/defer", &json!({"target": target, "minutes": minutes, "why": why, "owner": owner}))?;
    let left = r["deferred"]["until"].as_i64().map_or(0, |u| (u - chrono::Utc::now().timestamp()).max(0));
    println!("{target}'s deploy waits {} more min, and the other sessions at work are told", (left + 59) / 60);
    Ok(0)
}

pub fn deploy(target: Option<&str>, sha: Option<&str>, unverified: Option<&str>, no_wait: bool, owner: &str) -> Result<i32> {
    let Some(target) = target else {
        let o = client::get("/v1/deploys")?;
        println!("targets:");
        for t in o["targets"].as_array().into_iter().flatten() {
            println!("  {:<10} {:<20} built on {:<6} → {}", t["target"].as_str().unwrap_or("?"), t["repo"].as_str().unwrap_or("?"),
                t["machine"].as_str().unwrap_or("?"),
                t["publishes"].as_array().into_iter().flatten().filter_map(|p| p.as_str()).collect::<Vec<_>>().join(", "));
        }
        let ships: Vec<&Value> = o["ships"].as_array().into_iter().flatten().filter(|s| s["targets"].as_array().is_some_and(|t| !t.is_empty())).collect();
        if !ships.is_empty() {
            println!("after landings (the hub deploys these itself):");
            if let Some(by) = ships[0]["held"]["by"].as_str() {
                println!("  held by {by}{} — midas deploy --release", ships[0]["held"]["why"].as_str().map(|w| format!(": {w}")).unwrap_or_default());
            }
            for t in ships.iter().flat_map(|s| s["targets"].as_array().into_iter().flatten()) {
                println!("  {:<10} {}", t["target"].as_str().unwrap_or("?"), t["words"].as_str().unwrap_or(""));
            }
        }
        println!("the last week:");
        for e in o["recent"].as_array().into_iter().flatten() {
            println!("  {} {:<17} {} {}", e["ts"].as_str().unwrap_or("").get(..16).unwrap_or(""), e["kind"].as_str().unwrap_or(""),
                e["deploy"].as_str().unwrap_or(""), e["what"].as_str().map(|w| format!("— {}", w.lines().next().unwrap_or(""))).unwrap_or_default());
        }
        return Ok(0);
    };
    let req = client::post("/v1/deploy", &json!({
        "target": target, "sha": sha, "unverified": unverified, "owner": owner,
    }))?;
    let id = req["id"].as_str().context("the hub gave the deploy no id")?.to_string();
    let short = req["sha"].as_str().unwrap_or("").get(..8).unwrap_or("");
    match req["verified"]["node"].as_str() {
        Some(n) => println!("deploying {target} at {short} (verified on {n}) — {id}"),
        None => println!("deploying {target} at {short} — {id}"),
    }
    if no_wait {
        println!("follow it with: midas log --since 1h | grep {id}");
        return Ok(0);
    }
    // A build is minutes; a cold one, tens of them.
    let started = Instant::now();
    let mut seen = 0;
    loop {
        std::thread::sleep(Duration::from_secs(5));
        let st = match client::get(&format!("/v1/deploys/{id}")) {
            Ok(s) => s,
            Err(_) => continue, // the hub restarting is not the deploy failing
        };
        let evs = st["events"].as_array().cloned().unwrap_or_default();
        for e in evs.iter().skip(seen) {
            let kind = e["kind"].as_str().unwrap_or("");
            let line = match kind {
                "deploy_step" => format!("  {} {}{}", if e["ok"] == true { "✓" } else { "✗" }, e["step"].as_str().unwrap_or(""),
                    e["seconds"].as_u64().map(|s| format!(" ({s}s)")).unwrap_or_default()),
                "deploy_waiting" => format!("  · waiting for a {} node", e["machine"].as_str().unwrap_or("")),
                "deploy_build_start" => format!("  · building on {}", e["node"].as_str().unwrap_or("")),
                "deploy_built" => "  · built; publishing".into(),
                _ => continue,
            };
            println!("{line}");
            if let Some(t) = e["tail"].as_str() {
                for l in t.lines() {
                    println!("      {l}");
                }
            }
        }
        seen = evs.len();
        match st["state"].as_str() {
            Some("published") => {
                println!("published {target} at {short} in {}s", started.elapsed().as_secs());
                return Ok(0);
            }
            Some("failed") => {
                let what = evs.iter().rev().find(|e| e["kind"] == "deploy_failed").and_then(|e| e["what"].as_str()).unwrap_or("");
                eprintln!("deploy failed: {what}");
                return Ok(1);
            }
            _ => {}
        }
        if started.elapsed() > Duration::from_secs(3 * 3600) {
            eprintln!("still not done after three hours; it carries on — midas log --since 4h | grep {id}");
            return Ok(1);
        }
    }
}

/// `midas verified`: the landing gate passed at this commit.
pub fn verified(sha: Option<String>, steps: Option<String>, scope: Option<String>, node: Option<String>, owner: &str) -> Result<i32> {
    let sha = match sha {
        Some(s) => s,
        None => {
            let out = Command::new("git").args(["rev-parse", "HEAD"]).output()?;
            if !out.status.success() {
                bail!("not in a git checkout; give --sha");
            }
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        }
    };
    client::post("/v1/verified", &json!({"sha": sha, "steps": steps, "scope": scope, "node": node, "owner": owner}))?;
    println!("receipt recorded at the hub for {}", sha.get(..8).unwrap_or(&sha));
    Ok(0)
}

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

pub fn project_act(a: crate::ProjectCmd, owner: &str) -> Result<i32> {
    use crate::ProjectCmd as P;
    let enc = crate::hub::pct_encode;
    let repo_path = |r: &str| -> Result<String> {
        let r = crate::mirror::repo_name(r)?;
        Ok(r.trim_end_matches(".git").to_string())
    };
    let v = match a {
        P::Create { name, description, public, gate, gate_nodes, namespace } => client::post("/v1/projects/create", &json!({
            "owner": owner, "name": name, "description": description, "public": public,
            "gate": gate, "gate_nodes": gate_nodes, "repo_owner": namespace,
        }))?,
        P::Set { repo, gate, gate_nodes, pre_land, description, public, private } => {
            let mut b = json!({"owner": owner, "repo": repo_path(&repo)?});
            for (k, v) in [("gate", gate), ("gate_nodes", gate_nodes), ("pre_land", pre_land), ("description", description)] {
                if let Some(v) = v {
                    b[k] = json!(v);
                }
            }
            if public || private {
                b["public"] = json!(public);
            }
            client::post("/v1/projects/set", &b)?
        }
        P::Rename { repo, to } => client::post("/v1/projects/rename", &json!({"owner": owner, "repo": repo_path(&repo)?, "to": to}))?,
        P::Delete { repo } => client::post("/v1/projects/delete", &json!({"owner": owner, "repo": repo_path(&repo)?}))?,
        P::Show { repo, path, rev } => {
            let v = client::get(&format!("/v1/repos/{}/show?path={}{}", repo_path(&repo)?, enc(&path),
                rev.map(|r| format!("&rev={}", enc(&r))).unwrap_or_default()))?;
            match v["kind"].as_str() {
                Some("file") => print!("{}", v["text"].as_str().unwrap_or("(binary)\n")),
                _ => for e in v["entries"].as_array().into_iter().flatten() {
                    println!("{}{}", e["name"].as_str().unwrap_or("?"), if e["kind"] == "dir" { "/" } else { "" });
                },
            }
            return Ok(0);
        }
        P::Log { repo, rev, n } => {
            let v = client::get(&format!("/v1/repos/{}/log?n={n}{}", repo_path(&repo)?,
                rev.map(|r| format!("&rev={}", enc(&r))).unwrap_or_default()))?;
            for c in v.as_array().into_iter().flatten() {
                println!("{}  {}  {}", c["sha"].as_str().unwrap_or("").get(..10).unwrap_or(""),
                    c["at"].as_str().unwrap_or("").get(..10).unwrap_or(""), c["subject"].as_str().unwrap_or(""));
            }
            return Ok(0);
        }
    };
    println!("{}", serde_json::to_string_pretty(&v)?);
    Ok(0)
}

/// `midas hub git-key …`, on the hub as its user: the key list and the
/// `authorized_keys` written from it must stay the hub user's files.
/// Refuse to change the hub's files as anyone but the hub's user, so they stay its own.
fn as_hub_user(what: &str) -> Result<()> {
    let me = std::env::var("USER").unwrap_or_default();
    let hub_user = std::fs::metadata(crate::hosted::root().parent().unwrap_or(std::path::Path::new("/")))
        .map(|m| std::os::unix::fs::MetadataExt::uid(&m)).ok();
    // SAFETY: getuid has no preconditions.
    if hub_user.is_some_and(|u| u != unsafe { libc::getuid() }) {
        bail!("run it as the hub's user, so its files stay the hub's: sudo -u midas midas hub {what} … (you are {me:?})");
    }
    Ok(())
}

fn hub_actor() -> String {
    format!("hub:{}", std::env::var("SUDO_USER").or_else(|_| std::env::var("USER")).unwrap_or_default())
}

/// `midas hub import`: a Forgejo project into the hub (hosted::import).
pub fn hub_import(repo: &str, public: bool, description: &str, from: &crate::hosted::Source) -> Result<i32> {
    as_hub_user("import")?;
    let v = crate::hosted::import(repo, public, description, from, &hub_actor())?;
    println!("{}", serde_json::to_string_pretty(&v)?);
    let missing = v["lfs_missing"].as_array().map_or(0, Vec::len);
    if missing > 0 {
        eprintln!("{missing} LFS object(s) Forgejo could not give: a checkout of a commit that names one lacks that file");
    }
    eprintln!("next: close it to pushes at Forgejo, and point checkouts' origin at {} (docs/hub.md)", v["url"].as_str().unwrap_or(""));
    Ok(0)
}

pub fn git_key(c: crate::GitKeyCmd) -> Result<i32> {
    use crate::GitKeyCmd as K;
    if !matches!(c, K::List) {
        as_hub_user("git-key")?;
    }
    let by = hub_actor();
    match c {
        K::Add { name, role, key } => {
            crate::hosted::add_key(&name, &role, &key, &by)?;
            crate::hubsetup::refresh_ssh()?;
            eprintln!("{name} ({role}) may now push and fetch the hub's repositories: git@ is midas@{}", crate::conf::hub().ip());
        }
        K::Remove { name } => {
            if !crate::hosted::remove_key(&name, &by)? {
                bail!("no key {name}");
            }
            crate::hubsetup::refresh_ssh()?;
        }
        K::List => for (name, k) in crate::hosted::keys() {
            println!("{name}  {}  {}", k["role"].as_str().unwrap_or("?"), k["key"].as_str().unwrap_or("").get(..40).unwrap_or(""));
        },
    }
    Ok(0)
}