garage44.eu/jeroen/midas

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

.. /src/bot.rs

raw

//! Bot mode: a long-running program on a node, which its holder talks to over
//! MCP (DESIGN.md §2, "Bots").
//!
//! An agent takes a node **in bot mode** and starts a program there — a bot,
//! built from the node's checkout, which follows the agent's worktree as every
//! checkout does — then waits until it answers, and talks to it. MCP travels as
//! **stdio over an ssh session**: nodes allow no forwarding of any kind
//! (`node/sshd_config`), and a session's stdin and stdout are a perfectly good
//! pipe. The bot serves MCP on a Unix socket on the node and brings its own
//! stdio relay to that socket, so midas only ever runs two commands it is
//! given — how to start the bot, and how to reach it — and needs no HTTP
//! client, no port and no token of its own.
//!
//! * **Where agents work**: `midas bot start` takes the node in bot mode and
//!   runs `midas node bot start` there over ssh; `midas bot mcp` is the command
//!   an MCP client is configured with, and becomes `ssh <node> midas node bot
//!   mcp`; `midas bot stop` stops the bot and gives the node back.
//! * **On the node** (as `build`): `midas node bot start` runs the bot detached,
//!   in a session of its own, with `/config/bot.env` (the machine owner's
//!   secret, `midas bot setup`) in its environment, and returns once an MCP
//!   `initialize` through the relay is answered. Its record is
//!   `/work/bot/state.json`, its output `/work/bot/bot.log`.
//! * **A bot lives exactly as long as the bot lease that started it.** The
//!   heartbeat reports it, and a running bot renews its lease as an open session
//!   does (`registry::in_use`); the same heartbeat stops a bot whose lease has
//!   gone — released, lapsed, or taken for building — and the next holder's
//!   handover clears whatever is left.
//!
//! Both commands run under `bash -c`, not `-lc`: the session they are started
//! from is a login shell already (`midas node session`), and a second login
//! profile may read stdin — in a distrobox one did, and ate the relay's first
//! request.
//!
//! **Nothing on stdout but the protocol.** `midas bot mcp` and `midas node bot
//! mcp` hand stdout to MCP; every word midas says goes to stderr.

use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::os::fd::AsFd;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::cli::{self, Taken};
use crate::client;
use crate::node::{self, Lease};
use crate::mcp::PROTOCOL;
use crate::registry::{self, now, Mode};
use crate::util::short;

/// One readiness attempt: the relay started, `initialize` written, an answer
/// read. A bot that is up answers in milliseconds.
const ATTEMPT: Duration = Duration::from_secs(15);
/// Between attempts. A first `cargo run` compiles for many minutes; asking
/// every few seconds costs nothing and finds the bot soon after it listens.
const RETRY: Duration = Duration::from_secs(3);
/// How often a waiting `bot start` says where it is.
const PROGRESS: Duration = Duration::from_secs(30);
/// SIGTERM, then this long, then SIGKILL.
const GRACE: Duration = Duration::from_secs(10);
/// Lines of the bot's log shown when it fails, and by `status`.
const TAIL: usize = 30;

// ─── where agents work ───────────────────────────────────────────────────────

pub struct Start {
    pub take: cli::Take,
    /// The relay: a command whose stdin and stdout are the bot's MCP.
    pub mcp: String,
    /// How long the node waits for the bot to answer.
    pub timeout: u64,
    /// The bot.
    pub command: Vec<String>,
    /// An agent to host for it (`crate::host`), or none: the holder talks to
    /// the bot itself.
    pub agent: Option<AgentStart>,
}

/// `bot start --agent …`: what the host needs besides the node.
pub struct AgentStart {
    pub name: String,
    pub command: String,
    pub brief: Option<String>,
    pub meta: Option<Value>,
    pub inbox: String,
    pub idle_s: u64,
    pub mode: Option<String>,
}

/// The node this worktree holds, with its lease's mode.
fn held(owner: &str) -> Result<Option<(String, Mode)>> {
    let st = client::state()?;
    Ok(st["leases"].as_object().into_iter().flatten().find(|(_, l)| l["owner"] == owner)
        .map(|(id, l)| (id.clone(), registry::mode_of(l))))
}

/// A child's stdout sent to our stderr: what a node says while a bot starts is
/// for the person reading, and our stdout carries only the node's name.
fn to_stderr() -> Stdio {
    std::io::stderr().as_fd().try_clone_to_owned().map(Stdio::from).unwrap_or_else(|_| Stdio::null())
}

/// One word for a POSIX shell: as it is when it cannot be misread, else in
/// single quotes. The node's sshd hands the command to `bash -lc`, so this is
/// what makes every argument arrive as exactly the one it was.
pub fn sh_quote(s: &str) -> String {
    let plain = !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"_@%+=:,./-".contains(&b));
    if plain { s.to_string() } else { format!("'{}'", s.replace('\'', r"'\''")) }
}

/// The command `midas bot start` runs on the node, every argument quoted.
pub fn remote_command(relay: &str, timeout: u64, command: &[String], bot: Option<&str>) -> String {
    let mut s = format!("midas node bot start --timeout {timeout} --mcp {}{} --", sh_quote(relay),
                        bot.map(|b| format!(" --bot {}", sh_quote(b))).unwrap_or_default());
    for w in command {
        s.push(' ');
        s.push_str(&sh_quote(w));
    }
    s
}

/// `midas bot start`: take a node in bot mode, start the bot there, and wait
/// until it answers MCP. Prints the node's name on stdout, like `take`.
pub fn start(s: &Start) -> Result<i32> {
    if s.command.is_empty() {
        bail!("say what to start, after `--`: midas bot start --mcp '…' -- <command>");
    }
    if s.mcp.trim().is_empty() {
        bail!("--mcp is the command that relays MCP on stdio to the bot");
    }
    if let Some(a) = &s.agent {
        if !crate::host::name_ok(&a.name) {
            bail!("--name {:?}: letters, digits, - and _ only", a.name);
        }
        if let Some(pid) = crate::host::running(&a.name) {
            bail!("a bot named {} is hosted already (pid {pid}) — `midas bot stop --name {}` first, or another --name", a.name, a.name);
        }
    }
    // A node this worktree already held stays held if the bot fails to start;
    // one taken for the bot is given back.
    let before = held(&s.take.owner)?.map(|(id, _)| id);
    let id = match cli::take_node(&s.take)? {
        Taken::Node(id) => id,
        Taken::Queued => return Ok(cli::QUEUED),
    };
    // The hub's secrets for this node (`midas bot token`), and the bot's own
    // sign-in and voice key when the page configures one by this name
    // (Settings ▸ Bots, `botconfig`), are asked for by the node itself
    // (`node_start`), which the hub answers from the node's address and no
    // other: they never pass through this process, and until 2026-11-21 any
    // caller key could ask for any node's.
    let bot = s.agent.as_ref().map(|a| a.name.clone());
    // The flush runs before this ssh, as before any: the bot is built from
    // exactly the tree this worktree has.
    let st = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id])
        .arg(remote_command(&s.mcp, s.timeout, &s.command, bot.as_deref()))
        .stdin(Stdio::null())
        .stdout(to_stderr()).status().context("running ssh")?;
    if !st.success() {
        if before.as_deref() == Some(id.as_str()) {
            eprintln!("midas: no bot on {id}; this worktree held it before, and still does");
        } else {
            let _ = client::post_raw("/v1/release", &json!({"owner": s.take.owner, "node": id}));
            eprintln!("midas: no bot on {id}; gave it back");
        }
        return Ok(st.code().filter(|c| *c != 0).unwrap_or(1));
    }
    if let Some(a) = &s.agent {
        let cfg = crate::host::Config {
            name: a.name.clone(), owner: s.take.owner.clone(), node: id.clone(), agent: a.command.clone(),
            brief: a.brief.clone(), meta: a.meta.clone(), inbox: a.inbox.clone(), idle_s: a.idle_s, mode: a.mode.clone(), started_at: now(),
        };
        eprintln!("midas: the bot answers on {id}; starting its agent here (`{}`)", a.command);
        if let Err(e) = crate::host::launch(&cfg) {
            eprintln!("midas: its agent did not start: {e:#}");
            if before.as_deref() == Some(id.as_str()) {
                stop_remote(&id);
                eprintln!("midas: stopped the bot on {id}; this worktree held it before, and still does");
            } else {
                // Stops the bot as it gives the node back.
                let _ = cli::release(&s.take.owner, Some(&id), false);
            }
            return Ok(1);
        }
        eprintln!("bot {name} on {id} is up, its agent answering what it hears. It outlives this session. \
                   What it heard and did: midas bot log {name} · a line from you: midas bot tell {name} \"…\" · \
                   stop it and give the node back: midas bot stop --name {name}", name = a.name);
        println!("{id}");
        return Ok(0);
    }
    eprintln!("bot ready on {id}. Talk to it: midas bot mcp (an MCP server: {{\"command\": \"midas\", \"args\": [\"bot\", \"mcp\"]}}) \
               · its log: midas bot status · stop it and give the node back: midas bot stop");
    println!("{id}");
    Ok(0)
}

/// `midas bot mcp`: this worktree's bot, as an MCP server on stdio. Becomes
/// the ssh session to it, and says nothing on stdout itself.
pub fn mcp(owner: &str) -> Result<i32> {
    match held(owner)? {
        Some((id, Mode::Bot)) => {
            // MIDAS_FLUSHING: the bot was built when it started, and a relay
            // has nothing to send; nor need it be run from the holding
            // worktree (a host's agent runs it from a directory of its own).
            let err = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id, "midas node bot mcp"])
                .env("MIDAS_FLUSHING", "1").exec();
            bail!("could not run ssh: {err}")
        }
        Some((id, Mode::Build | Mode::Job)) => {
            eprintln!("midas bot mcp: this worktree ({owner}) holds {id} for building, with no bot — midas bot start …");
            Ok(1)
        }
        None => {
            eprintln!("midas bot mcp: this worktree ({owner}) holds no node — midas bot start …");
            Ok(1)
        }
    }
}

/// Ask a node to stop its bot. Best effort and quick: a node that does not
/// answer stops a bot whose lease has gone by itself, within a minute.
pub fn stop_remote(node: &str) -> bool {
    // MIDAS_FLUSHING: no flush and no holder check for this one — stopping
    // needs no worktree, and a release should not first send one.
    let ok = Command::new("ssh").args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--", node, "midas node bot stop"])
        .env("MIDAS_FLUSHING", "1").stdin(Stdio::null()).stdout(to_stderr()).status()
        .is_ok_and(|s| s.success());
    if !ok {
        eprintln!("midas: could not reach {node} to stop its bot; the node stops it by itself within a minute of the release");
    }
    ok
}

/// `midas bot stop`: stop this worktree's bot (or the hosted bot `name`) and
/// give its node back. A hosted bot's host does both as it ends.
pub fn stop(owner: &str, name: Option<&str>) -> Result<i32> {
    let mut owner = owner.to_string();
    if let Some(cfg) = crate::host::find(name, &owner) {
        owner = cfg.owner.clone();
        if crate::host::stop(&cfg.name) {
            eprintln!("stopped {} and its agent", cfg.name);
            if held(&owner)?.is_none() {
                return Ok(0);
            }
        }
    } else if let Some(n) = name {
        eprintln!("no hosted bot named {n} here");
        return Ok(1);
    }
    let owner = owner.as_str();
    match held(owner)? {
        // `release` stops a bot lease's bot first.
        Some((_, Mode::Bot)) => cli::release(owner, None, false),
        Some((id, Mode::Build | Mode::Job)) => {
            eprintln!("this worktree holds {id} for building, with no bot; `midas release` gives it back");
            Ok(1)
        }
        None => {
            eprintln!("this worktree ({owner}) holds no node");
            Ok(1)
        }
    }
}

/// `midas bot status`: what the node says about this worktree's bot (or the
/// hosted bot `name`), and how its host is.
pub fn status(owner: &str, name: Option<&str>) -> Result<i32> {
    let mut owner = owner.to_string();
    if let Some(cfg) = crate::host::find(name, &owner) {
        println!("{}", crate::host::describe(&cfg));
        owner = cfg.owner;
    }
    let owner = owner.as_str();
    let Some((id, mode)) = held(owner)? else {
        eprintln!("this worktree ({owner}) holds no node");
        return Ok(1);
    };
    println!("{id}, held in {} mode", mode.as_str());
    let st = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id, "midas node bot status"])
        .env("MIDAS_FLUSHING", "1").stdin(Stdio::null()).status().context("running ssh")?;
    Ok(st.code().unwrap_or(1))
}

// ─── the node's side ─────────────────────────────────────────────────────────

/// What `midas node bot start` started: enough to find it again, stop it, and
/// reach it.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct State {
    pub pid: u32,
    /// Its own session and process group: everything the bot started.
    pub pgid: u32,
    /// The process's start time, in clock ticks since boot, so a pid used
    /// again by something else is never taken for the bot.
    #[serde(default)]
    pub ticks: Option<u64>,
    /// The command, as bash ran it.
    pub start: String,
    /// The relay to it.
    pub relay: String,
    pub started_at: i64,
    /// The lease it belongs to, `<owner> <claimed_at>`: a bot outlives no lease.
    pub lease: String,
}

fn bot_dir() -> PathBuf {
    PathBuf::from(std::env::var("MIDAS_BOT_DIR").unwrap_or_else(|_| "/work/bot".into()))
}

fn checkout() -> PathBuf {
    PathBuf::from(std::env::var("MIDAS_CHECKOUT").unwrap_or_else(|_| node::CHECKOUT.into()))
}

fn state_path() -> PathBuf {
    bot_dir().join("state.json")
}

fn log_path() -> PathBuf {
    bot_dir().join("bot.log")
}

fn read_state() -> Option<State> {
    fs::read_to_string(state_path()).ok().and_then(|t| serde_json::from_str(&t).ok())
}

fn write_state(st: &State) -> Result<()> {
    let tmp = state_path().with_extension("tmp");
    fs::write(&tmp, serde_json::to_string_pretty(st)?)?;
    fs::rename(&tmp, state_path())?;
    Ok(())
}

/// The fields of `/proc/<pid>/stat` after the command's closing parenthesis:
/// state, ppid, pgrp, … starttime is the 20th of them.
fn stat(pid: u32) -> Option<Vec<String>> {
    let t = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    Some(t.rsplit_once(')')?.1.split_whitespace().map(str::to_string).collect())
}

fn start_ticks(pid: u32) -> Option<u64> {
    stat(pid)?.get(19)?.parse().ok()
}

fn has_proc() -> bool {
    Path::new("/proc/self/stat").exists()
}

/// Is this process the one that was started, and not yet dead?
fn alive(pid: u32, ticks: Option<u64>) -> bool {
    if !has_proc() {
        // SAFETY: kill(2) with signal 0 only asks whether the pid exists.
        return unsafe { libc::kill(pid as i32, 0) } == 0;
    }
    stat(pid).is_some_and(|f| {
        !matches!(f.first().map(String::as_str), Some("Z" | "X")) && (ticks.is_none() || f.get(19).and_then(|t| t.parse().ok()) == ticks)
    })
}

/// Is anything of the bot's process group still running (zombies aside)?
fn group_alive(st: &State) -> bool {
    if st.pgid <= 1 {
        return false;
    }
    // The leader's number taken by an unrelated process since: not ours.
    if let (Some(then), Some(now)) = (st.ticks, start_ticks(st.pgid)) {
        if then != now {
            return false;
        }
    }
    if !has_proc() {
        // SAFETY: signal 0 to a process group asks whether it has members.
        return unsafe { libc::kill(-(st.pgid as i32), 0) } == 0;
    }
    let pg = st.pgid.to_string();
    fs::read_dir("/proc").into_iter().flatten().flatten()
        .filter_map(|e| e.file_name().to_str()?.parse::<u32>().ok())
        .filter_map(stat)
        .any(|f| f.get(2) == Some(&pg) && !matches!(f.first().map(String::as_str), Some("Z" | "X")))
}

/// The bot, if one is running.
pub fn running() -> Option<State> {
    read_state().filter(|s| alive(s.pid, s.ticks))
}

/// SIGTERM to the whole group, SIGKILL after [`GRACE`]. Returns whether it
/// took the SIGKILL.
fn stop_group(st: &State) -> bool {
    if st.pgid <= 1 || !group_alive(st) {
        return false;
    }
    let signal = |sig| {
        // SAFETY: kill(2) on a process group this user started, pgid > 1.
        unsafe { libc::kill(-(st.pgid as i32), sig) };
    };
    signal(libc::SIGTERM);
    let until = Instant::now() + GRACE;
    while Instant::now() < until {
        if !group_alive(st) {
            return false;
        }
        std::thread::sleep(Duration::from_millis(200));
    }
    signal(libc::SIGKILL);
    let until = Instant::now() + Duration::from_secs(2);
    while group_alive(st) && Instant::now() < until {
        std::thread::sleep(Duration::from_millis(100));
    }
    true
}

/// Lines `NAME=value` from `bot.env`; blank lines and `#` comments skipped, and
/// a value in matching quotes taken without them.
pub fn parse_env(text: &str) -> Vec<(String, String)> {
    text.lines().filter_map(|l| {
        let l = l.trim();
        if l.is_empty() || l.starts_with('#') {
            return None;
        }
        let (k, v) = l.split_once('=')?;
        let k = k.trim().trim_start_matches("export ").trim();
        if !env_name_ok(k) {
            return None;
        }
        let v = v.trim();
        let unquoted = [('"', '"'), ('\'', '\'')].iter()
            .find_map(|(a, b)| v.strip_prefix(*a).and_then(|r| r.strip_suffix(*b)))
            .filter(|_| v.len() >= 2);
        Some((k.to_string(), unquoted.unwrap_or(v).to_string()))
    }).collect()
}

/// An environment variable's name: letters, digits and `_`, not starting with a digit.
pub fn env_name_ok(k: &str) -> bool {
    !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}

/// The machine owner's secrets for the bot (`midas bot setup`), if there are any.
fn bot_env() -> Result<Vec<(String, String)>> {
    let path = node::config_dir().join("bot.env");
    match fs::read_to_string(&path) {
        Ok(t) => Ok(parse_env(&t)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(vec![]),
        Err(e) => Err(e).with_context(|| format!("reading {} (the owner sets it: sudo midas bot setup)", path.display())),
    }
}

/// The bot's command line: one word is a shell command as it stands (`--
/// 'make run'`), several are an argument list, each kept as it was given.
pub fn shell_line(command: &[String]) -> String {
    match command {
        [one] => one.clone(),
        many => many.iter().map(|w| sh_quote(w)).collect::<Vec<_>>().join(" "),
    }
}

/// The last `n` lines of a file that may be large (a build's output).
fn tail(path: &Path, n: usize) -> Vec<String> {
    let Ok(mut f) = fs::File::open(path) else { return vec![] };
    let len = f.metadata().map(|m| m.len()).unwrap_or(0);
    let _ = f.seek(SeekFrom::Start(len.saturating_sub(64 * 1024)));
    let mut buf = Vec::new();
    let _ = f.read_to_end(&mut buf);
    let text = String::from_utf8_lossy(&buf);
    let lines: Vec<String> = text.lines().filter(|l| !l.trim().is_empty()).map(str::to_string).collect();
    lines[lines.len().saturating_sub(n)..].to_vec()
}

fn show_tail(why: &str) {
    eprintln!("midas: {why} — the last of {}:", log_path().display());
    for l in tail(&log_path(), TAIL) {
        eprintln!("  | {l}");
    }
}

/// Is the bot up? Start the relay, write one MCP `initialize`, and wait up to
/// `wait` for the answer: a JSON-RPC response with the same id and a `result`.
/// The relay runs in a process group of its own and is ended with it.
pub fn handshake(relay: &str, cwd: &Path, wait: Duration) -> Result<()> {
    let mut c = Command::new("bash");
    c.arg("-c").arg(relay).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
    // SAFETY: setpgid in the child before exec, async-signal-safe.
    unsafe {
        c.pre_exec(|| {
            libc::setpgid(0, 0);
            Ok(())
        });
    }
    let mut child = c.spawn().context("starting the relay")?;
    let pgid = child.id() as i32;
    let (tx, rx) = mpsc::channel::<String>();
    let out = child.stdout.take().unwrap();
    std::thread::spawn(move || {
        for line in BufReader::new(out).lines().map_while(Result::ok) {
            if tx.send(line).is_err() {
                break;
            }
        }
    });
    let said = Arc::new(Mutex::new(String::new()));
    let err = child.stderr.take().unwrap();
    let said2 = said.clone();
    std::thread::spawn(move || {
        for line in BufReader::new(err).lines().map_while(Result::ok) {
            if !line.trim().is_empty() {
                *said2.lock().unwrap() = line;
            }
        }
    });
    let request = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
        "protocolVersion": PROTOCOL, "capabilities": {},
        "clientInfo": {"name": "midas", "version": crate::VERSION}}});
    // Held open until the answer: a relay may end when its stdin does, before
    // the bot has answered.
    let mut stdin = child.stdin.take();
    let wrote = stdin.as_mut().map(|s| writeln!(s, "{request}").and_then(|_| s.flush()));
    let deadline = Instant::now() + wait;
    let outcome = loop {
        if !matches!(wrote, Some(Ok(()))) {
            break Err("the relay would not take the request".to_string());
        }
        match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
            Ok(line) => {
                let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
                if v["id"] != 1 {
                    continue;
                }
                if v.get("result").is_some() {
                    break Ok(());
                }
                break Err(format!("the bot answered with an error: {}", v["error"]));
            }
            Err(mpsc::RecvTimeoutError::Timeout) => break Err(format!("no answer in {}s", wait.as_secs())),
            Err(mpsc::RecvTimeoutError::Disconnected) => break Err("the relay ended without an answer".into()),
        }
    };
    drop(stdin);
    // SAFETY: kill(2) on the relay's own process group (pgid > 1, ours).
    if pgid > 1 {
        unsafe { libc::kill(-pgid, libc::SIGKILL) };
    }
    let _ = child.wait();
    outcome.map_err(|why| {
        std::thread::sleep(Duration::from_millis(50));
        let said = said.lock().unwrap().clone();
        if said.is_empty() { anyhow::anyhow!(why) } else { anyhow::anyhow!("{why}; the relay said: {said}") }
    })
}

/// `midas node bot start`: start the bot detached, and return when it answers.
pub fn node_start(relay: &str, timeout: u64, command: &[String], env_stdin: bool, bot: Option<&str>) -> Result<i32> {
    // A relay that ends before taking the request must cost the request, not
    // this process: with SIGPIPE at its default a write to it would end us.
    // SAFETY: setting a signal's disposition.
    unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
    let cfg = node::config();
    let lease = match node::lease(&cfg) {
        Lease::Held { mode, owner, since, .. } if mode == Mode::Bot.as_str() => format!("{owner} {since}"),
        Lease::Held { owner, .. } => bail!("{} is held by {owner} for building, not for a bot — `midas bot start` takes a node in bot mode", cfg.node),
        Lease::Free => bail!("{} is not leased — `midas bot start` takes it in bot mode first", cfg.node),
        Lease::Unknown(why) => bail!("could not ask the hub whether {} is leased for a bot ({why}); not starting one", cfg.node),
    };
    if let Some(st) = running() {
        bail!("a bot is already running here (pid {}, since {}): {} — `midas bot stop` stops it",
              st.pid, cli::ago(st.started_at), short(&st.start, 80));
    }
    if command.is_empty() {
        bail!("no command to start");
    }
    let cwd = checkout();
    if !cwd.is_dir() {
        bail!("no checkout at {} yet", cwd.display());
    }
    fs::create_dir_all(bot_dir())?;
    // Whatever an earlier bot left (one that exited by itself) is stopped for good.
    if let Some(old) = read_state() {
        stop_group(&old);
    }
    let _ = fs::remove_file(state_path());
    let mut env = bot_env()?;
    // The hub's secrets for this node, and the bot's own (Settings ▸ Bots), after
    // the machine's: a name set in both takes the hub's. Asked for by this node,
    // which the hub answers from its address only; they go into the bot's
    // environment and nowhere else.
    match crate::hub::request(&cfg.hub, "POST", "/v1/bot/secrets/for", Some(&json!({"node": cfg.node, "bot": bot}).to_string())) {
        Ok((200, body)) => {
            let given = serde_json::from_str::<Value>(&body).ok().and_then(|v| v["env"].as_object().cloned()).unwrap_or_default();
            for (k, v) in given {
                if let Some(v) = v.as_str() {
                    env.retain(|(name, _)| *name != k);
                    env.push((k, v.to_string()));
                }
            }
        }
        Ok((code, body)) => eprintln!("midas: the hub gave {} no secrets (HTTP {code}): {}", cfg.node, body.trim()),
        Err(e) => eprintln!("midas: the hub gave {} no secrets: {e:#}", cfg.node),
    }
    if env_stdin {
        // The hub's, after the machine's: a name set in both takes the hub's.
        let mut text = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin().take(64 * 1024), &mut text)?;
        for (k, v) in parse_env(&text) {
            env.retain(|(name, _)| *name != k);
            env.push((k, v));
        }
    }
    let script = shell_line(command);
    let mut log = OpenOptions::new().create(true).append(true).open(log_path())
        .with_context(|| format!("opening {}", log_path().display()))?;
    writeln!(log, "--- midas {}: starting `{script}` in {}{}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), cwd.display(),
        if env.is_empty() { String::new() } else { format!(" with {} in its environment", env.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(", ")) })?;
    let mut c = Command::new("bash");
    c.arg("-c").arg(&script).current_dir(&cwd).envs(env.iter().map(|(k, v)| (k, v)))
        .stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
    // Its own session: no terminal, no ssh session to be hung up with, and one
    // process group that `stop` ends whole.
    // SAFETY: setsid in the child before exec, async-signal-safe.
    unsafe {
        c.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    let mut child = c.spawn().context("starting the bot")?;
    let pid = child.id();
    let st = State {
        pid, pgid: pid, ticks: start_ticks(pid), start: script.clone(), relay: relay.to_string(),
        started_at: now(), lease,
    };
    write_state(&st)?;
    node::emit(&cfg, "bot_started", json!({
        "pid": pid, "command": short(&script, 200), "relay": short(relay, 200),
        // Names only: the values are the owner's secrets.
        "env": env.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
    }));
    eprintln!("midas: bot started on {} (pid {pid}, log {}); waiting for it to answer MCP through `{relay}`",
              cfg.node, log_path().display());

    let started = Instant::now();
    let mut said = Instant::now();
    loop {
        if let Some(exit) = child.try_wait()? {
            let _ = fs::remove_file(state_path());
            stop_group(&st);
            node::emit(&cfg, "bot_failed", json!({"why": "exited before it answered", "exit": exit.code(),
                                                  "after_s": started.elapsed().as_secs()}));
            show_tail(&format!("the bot exited ({exit}) before it answered"));
            bail!("no bot: it exited after {}s", started.elapsed().as_secs());
        }
        let last_err = match handshake(relay, &cwd, ATTEMPT) {
            Ok(()) => break,
            Err(e) => format!("{e:#}"),
        };
        if started.elapsed() >= Duration::from_secs(timeout) {
            stop_group(&st);
            let _ = fs::remove_file(state_path());
            node::emit(&cfg, "bot_failed", json!({"why": "did not answer in time", "timeout_s": timeout, "relay": last_err}));
            show_tail(&format!("the bot did not answer in {timeout}s ({last_err}); stopped it"));
            bail!("no bot: it did not answer in {timeout}s");
        }
        if said.elapsed() >= PROGRESS {
            said = Instant::now();
            eprintln!("midas: {}s, not answering yet ({last_err}) — log: {}", started.elapsed().as_secs(),
                      tail(&log_path(), 1).first().map(|l| short(l, 160)).unwrap_or_else(|| "(empty)".into()));
        }
        std::thread::sleep(RETRY);
    }
    let after = started.elapsed().as_secs();
    node::emit(&cfg, "bot_ready", json!({"pid": pid, "after_s": after}));
    eprintln!("midas: the bot answers MCP (after {after}s)");
    Ok(0)
}

/// `midas node bot mcp`: become the relay to the running bot. stdin and stdout
/// pass straight through; midas says nothing on stdout.
pub fn node_mcp() -> Result<i32> {
    let Some(st) = running() else {
        eprintln!("midas: no bot is running on this node — midas bot start …");
        return Ok(1);
    };
    let err = Command::new("bash").arg("-c").arg(&st.relay).current_dir(checkout()).exec();
    bail!("could not start the relay: {err}")
}

/// `midas node bot stop`: stop the bot, whole process group. Idempotent.
pub fn node_stop() -> Result<i32> {
    let Some(st) = read_state() else {
        eprintln!("midas: no bot here");
        return Ok(0);
    };
    if group_alive(&st) {
        let killed = stop_group(&st);
        let cfg = node::config();
        node::emit(&cfg, "bot_stopped", json!({"why": "asked", "command": short(&st.start, 200),
                                              "up_s": now() - st.started_at, "killed": killed}));
        eprintln!("midas: stopped the bot (pid {}, up {}){}", st.pid, cli::ago(st.started_at).trim_end_matches(" ago"),
                  if killed { ", with SIGKILL after it ignored SIGTERM" } else { "" });
    } else {
        eprintln!("midas: the bot had already exited");
    }
    let _ = fs::remove_file(state_path());
    Ok(0)
}

/// `midas node bot status`: running?, since, command, the last of its log.
pub fn node_status() -> Result<i32> {
    let st = read_state();
    let up = st.as_ref().is_some_and(|s| alive(s.pid, s.ticks));
    match &st {
        Some(s) if up => println!("bot running since {} (pid {})", cli::ago(s.started_at), s.pid),
        Some(s) => println!("bot exited (started {})", cli::ago(s.started_at)),
        None => println!("no bot"),
    }
    if let Some(s) = &st {
        println!("  start: {}\n  relay: {}", s.start, s.relay);
    }
    let lines = tail(&log_path(), TAIL);
    if !lines.is_empty() {
        println!("  {}:", log_path().display());
        for l in lines {
            println!("  | {l}");
        }
    }
    Ok(if up { 0 } else { 1 })
}

/// The bot, for the heartbeat: short, and nothing secret.
pub fn reading() -> Value {
    match running() {
        Some(s) => json!({"running": true, "since": s.started_at, "command": short(&s.start, 60)}),
        None => Value::Null,
    }
}

/// The heartbeat's rule: a bot runs only under the bot lease that started it.
/// Released, lapsed, or taken again — for building, or by anyone else — it is
/// stopped. A hub that does not answer stops nothing.
pub fn enforce(cfg: &node::Config) {
    let Some(st) = running() else { return };
    let why = match node::lease(cfg) {
        Lease::Held { mode, owner, since, .. } => {
            if mode == Mode::Bot.as_str() && format!("{owner} {since}") == st.lease {
                return;
            }
            if mode == Mode::Bot.as_str() { format!("the node is held by another lease ({owner})") }
            else { format!("the node was taken for building ({owner})") }
        }
        Lease::Free => "the node is no longer leased".into(),
        Lease::Unknown(_) => return,
    };
    let killed = stop_group(&st);
    let _ = fs::remove_file(state_path());
    node::emit(cfg, "bot_stopped", json!({"why": why, "lease": st.lease, "command": short(&st.start, 200),
                                         "up_s": now() - st.started_at, "killed": killed}));
}

/// The handover's part: whatever is left of the previous holder's bot is
/// stopped, and its record and log removed. Returns whether there was one.
pub fn clear() -> bool {
    let had = read_state();
    if let Some(st) = &had {
        stop_group(st);
    }
    let _ = fs::remove_dir_all(bot_dir());
    had.is_some()
}

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

    #[test]
    fn every_argument_reaches_the_node_as_it_was() {
        assert_eq!(sh_quote("cargo"), "cargo");
        assert_eq!(sh_quote("unix:/tmp/bot/mcp.sock"), "unix:/tmp/bot/mcp.sock");
        assert_eq!(sh_quote(""), "''");
        assert_eq!(sh_quote("it's $HOME; rm -rf ~"), r"'it'\''s $HOME; rm -rf ~'");
        let cmd: Vec<String> = ["cargo", "run", "-q", "--", "--name", "a b", "$X", "it's"].map(String::from).to_vec();
        let remote = remote_command("socat - UNIX:/tmp/s", 60, &cmd, None);
        assert!(remote_command("r", 60, &cmd, Some("scout")).contains(" --bot scout --"), "the bot's name, before the command");
        assert!(remote_command("r", 60, &cmd, Some("a b")).contains(" --bot 'a b' --"));
        assert!(!remote.contains("--env-stdin"));
        // What the node's `bash -lc` makes of it is exactly the argument list.
        let out = Command::new("bash").arg("-c").arg(format!("printf '%s\\n' {}", remote.trim_start_matches("midas ")))
            .output().unwrap();
        let words: Vec<String> = String::from_utf8_lossy(&out.stdout).lines().map(str::to_string).collect();
        let mut want: Vec<String> = ["node", "bot", "start", "--timeout", "60", "--mcp", "socat - UNIX:/tmp/s", "--"]
            .map(String::from).to_vec();
        want.extend(cmd);
        assert_eq!(words, want);
    }

    #[test]
    fn one_word_is_a_shell_command_and_several_an_argument_list() {
        assert_eq!(shell_line(&["make run && echo ok".into()]), "make run && echo ok");
        assert_eq!(shell_line(&["echo".into(), "a b".into(), "c".into()]), "echo 'a b' c");
    }

    #[test]
    fn bot_env_is_names_and_values_and_nothing_else() {
        let e = parse_env("# set by midas bot setup\nCARTO_TOKEN=abc=def\n\n  export OTHER = \"q v\"\n1BAD=x\nnot a line\nEMPTY=\nQ='x'\n");
        assert_eq!(e, vec![
            ("CARTO_TOKEN".into(), "abc=def".into()),
            ("OTHER".into(), "q v".into()),
            ("EMPTY".into(), String::new()),
            ("Q".into(), "x".into()),
        ]);
        assert!(env_name_ok("CARTO_TOKEN") && env_name_ok("_x1"));
        assert!(!env_name_ok("1X") && !env_name_ok("A-B") && !env_name_ok(""));
    }

    /// A fake relay: a bot that is up after `ready_after` attempts (counted in
    /// a file), or never.
    fn relay(dir: &Path, ready_after: u32, answer: &str) -> String {
        let script = dir.join("relay.sh");
        fs::write(&script, format!(r#"#!/bin/bash
n=$(cat "{d}/attempts" 2>/dev/null || echo 0); n=$((n+1)); echo $n > "{d}/attempts"
if [ "$n" -le {ready_after} ]; then echo "connect: no such file" >&2; exit 1; fi
read -r line
case "$line" in *'"initialize"'*) ;; *) echo "not an initialize: $line" >&2; exit 1 ;; esac
echo 'a banner that is not JSON'
echo '{{"jsonrpc":"2.0","method":"notifications/message","params":{{}}}}'
echo '{answer}'
sleep 30
"#, d = dir.display())).unwrap();
        format!("bash {}", script.display())
    }

    #[test]
    fn the_handshake_waits_for_the_answer_to_its_own_initialize() {
        let dir = tempfile::tempdir().unwrap();
        let r = relay(dir.path(), 2, r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18"}}"#);
        let e = handshake(&r, dir.path(), Duration::from_secs(5)).unwrap_err();
        assert!(format!("{e:#}").contains("connect: no such file"), "the relay's own complaint is passed on: {e:#}");
        assert!(handshake(&r, dir.path(), Duration::from_secs(5)).is_err());
        let t = Instant::now();
        handshake(&r, dir.path(), Duration::from_secs(5)).unwrap();
        assert!(t.elapsed() < Duration::from_secs(3), "the relay is ended once it has answered, not waited for");
    }

    #[test]
    fn an_error_or_silence_is_not_ready() {
        let dir = tempfile::tempdir().unwrap();
        let r = relay(dir.path(), 0, r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"starting"}}"#);
        assert!(format!("{:#}", handshake(&r, dir.path(), Duration::from_secs(5)).unwrap_err()).contains("starting"));
        let mute = handshake("cat >/dev/null", dir.path(), Duration::from_millis(500)).unwrap_err();
        assert!(format!("{mute:#}").contains("no answer"), "{mute:#}");
        let wrong = handshake(r#"read -r l; echo '{"jsonrpc":"2.0","id":2,"result":{}}'; sleep 5"#, dir.path(), Duration::from_millis(800));
        assert!(wrong.is_err(), "an answer to some other request is not the answer");
    }

    // A process's start time is read from /proc: Linux only, so a landing gated on a Mac node passes without it.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_stopped_bot_takes_its_whole_process_group_with_it() {
        let dir = tempfile::tempdir().unwrap();
        // A bot whose child ignores SIGTERM: the group still ends, by SIGKILL.
        let mut c = Command::new("bash");
        c.arg("-c").arg("(trap '' TERM; sleep 60) & sleep 60").stdout(Stdio::null());
        unsafe { c.pre_exec(|| { libc::setsid(); Ok(()) }); }
        let mut child = c.spawn().unwrap();
        let pid = child.id();
        std::thread::sleep(Duration::from_millis(200));
        let st = State { pid, pgid: pid, ticks: start_ticks(pid), start: "x".into(), relay: "y".into(), started_at: now(), lease: "a 1".into() };
        assert!(alive(pid, st.ticks) && group_alive(&st));
        assert!(!alive(pid, st.ticks.map(|t| t + 1)), "a different start time is a different process");
        assert!(stop_group(&st), "the TERM-proof child needed the KILL");
        let _ = child.wait();
        assert!(!group_alive(&st));
        let _ = dir;
    }
}

/// `midas bot token`: set, remove or list the hub's secrets for bots.
pub fn token(target: Option<&str>, name: &str, stdin: bool, remove: bool, list: bool) -> Result<i32> {
    if list {
        let v = client::get_auth("/v1/bot/secrets")?;
        let m = v.as_object().cloned().unwrap_or_default();
        if m.is_empty() {
            println!("no bot secrets at the hub");
        }
        for (node, names) in m {
            println!("{node:<8} {}", names.as_array().into_iter().flatten().filter_map(|n| n.as_str()).collect::<Vec<_>>().join(", "));
        }
        return Ok(0);
    }
    let target = target.context("say for which: a node, a machine, gpu or any")?;
    let value = if remove {
        None
    } else if stdin {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).context("reading the secret from stdin")?;
        Some(line.trim().to_string())
    } else {
        // SAFETY: isatty on a descriptor every process has.
        if unsafe { libc::isatty(0) } != 1 {
            bail!("stdin is not a terminal; to read the secret from a pipe, add --stdin");
        }
        Some(crate::botsetup::read_hidden(&format!("{name} for the bots on {target} (not shown): "))?.trim().to_string())
    };
    if value.as_deref() == Some("") {
        bail!("nothing entered; nothing stored");
    }
    let r = client::post("/v1/bot/secrets", &json!({
        "target": target, "name": name, "value": value, "remove": remove, "owner": cli::owner(),
    }))?;
    let nodes = r["nodes"].as_array().into_iter().flatten().filter_map(|n| n.as_str()).collect::<Vec<_>>().join(", ");
    if remove {
        println!("removed {name} for {nodes}");
    } else {
        println!("{name} set for {nodes}: a bot started there from now on has it in its environment");
    }
    Ok(0)
}