garage44.eu/jeroen/midas

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

.. /src/hub.rs

raw

//! The hub: the one process that holds the workspace's state, and the HTTP API
//! everything else uses (`client`), on the WireGuard address only.
//!
//! * reads (open): `GET /v1/health`, `/v1/state`, `/v1/events?…`,
//!   `/v1/position?owner=`, `/v1/lease/<node>`, and the history:
//!   `/v1/builds`, `/v1/history`, `/v1/landings`, `/v1/sessions` (`?since=` s);
//!   `/v1/usage?since=&step=` (each node's memory, load and disk over time: usage.rs);
//!   `/v1/names`, `/v1/notes/count?owner=`, `/v1/reservations`, `/v1/todos` and
//!   `/v1/decisions` (collab.rs); `/v1/hosted/stats?since=` (every session's
//!   conversation, counted: sessions.rs `stats`); `/v1/hosted/discuss` (whether a session can
//!   be talked over by voice: `POST` it, with the steer role, to open the call);
//!   `/v1/settings` (the page's Settings; `POST /v1/settings/discuss`,
//!   `/v1/settings/openai_key`, `/v1/settings/agent` and `GET /v1/settings/models` take the admin role);
//!   `/v1/hosted/agents` (the agents a session may run, by name: agents.rs);
//! * agents' memory (memory.rs), for a caller key with the operator role:
//!   `GET /v1/memory?repo=` (without `repo`: every set, for the page),
//!   `POST /v1/memory`;
//! * the web page (`web.rs`): `GET /` and its two files;
//! * from nodes, accepted only from the node's own WireGuard address:
//!   `POST /v1/renew/<node>`, `/v1/readings/<node>` (the heartbeat),
//!   `/v1/nodes/<node>/register` (its git and host keys), `GET /v1/nodes/<node>/midas`
//!   and `/v1/nodes/<node>/midas/<os-arch>` (the midas it should run), `/v1/bot/secrets/for`
//!   (the secrets a bot there starts with), and its `ssh_session` lines to `/v1/events` — which
//!   is otherwise open for a plain log line, but acts on a kind in `events::drives_state` only
//!   from a caller key;
//!   and from a machine's address, `POST /v1/power` (what it draws: power.rs, read
//!   back with the open `GET /v1/power?since=&step=`), and `POST /v1/sleep` (which
//!   of its VMs to keep running: sleep.rs);
//! * from the git server's post-receive hook, on the hub's own address only:
//!   `POST /v1/pushed` (a branch moved; the mirror is fetched at once);
//! * for a node being set up (open, all public): `GET /v1/nodes/<node>/config`;
//! * changes (a caller key from `/srv/midas/callers.json`): `POST /v1/claim`
//!   (with a `mode`: `build`, the default, `bot` or `job`),
//!   `/v1/release`, `/v1/renew`, `/v1/unqueue`, `/v1/say`, `/v1/notes/take`, `/v1/notes/confirm`, `/v1/notes/sent`,
//!   `/v1/work`, `/v1/editing`, `/v1/intent`, `/v1/yield`, `/v1/next`, `/v1/reserve`, `/v1/todos/{add,take,done}`,
//!   `/v1/decisions/{add,answer}` (sessions working together), `/v1/land/{claim,renew,release}`
//!   (the landing queue), `/v1/drain`, `/v1/nodes/add`,
//!   `/v1/nodes/remove`, `/v1/nodes/rename`, `/v1/deploy`, `/v1/deploy/hold`,
//!   `/v1/deploy/release`, `/v1/push/subscribe`, `/v1/push/unsubscribe`, `/v1/push/ntfy`,
//!   `/v1/push/ntfy/test`, `/v1/verified`;
//!   and reading deploys: `GET /v1/deploys`, `/v1/deploys/<id>`; the bots'
//!   secrets: `POST /v1/bot/secrets`, `/v1/bot/secrets/for`, `GET /v1/bot/secrets`
//!   (names only), all three behind a caller key;
//! * paired devices (device.rs): `GET /v1/devices`, `/v1/devices/<id>` (open
//!   reads); `POST /v1/devices/code` (a person's), `/v1/devices/forget`,
//!   `/v1/devices/call` (a session's machine's key); and a device's own, with its
//!   token in `X-Midas-Device`: `POST /v1/device/pair` (open: the code is the
//!   credential), `GET /v1/device/me`, `/v1/device/sessions`, `POST /v1/device/push`
//!   and `GET /v1/device/link`, a WebSocket;
//! * `/v1/forgejo/<api path>`: a Forgejo call with the token held for the
//!   caller's key; `/lfs/…`: LFS for nodes.
//!
//! It runs as the unprivileged `midas` user under systemd confinement, because
//! the nodes it answers run untrusted builds. Std-only, one thread per
//! connection: a handful of nodes and agents do not need an async runtime.

use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

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

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

const MAX_BODY: usize = 64 * 1024;

pub fn serve(listen: Option<&str>) -> Result<i32> {
    let conf = crate::conf::hub();
    let listen = listen.unwrap_or(&conf.listen);
    let listener = TcpListener::bind(listen).with_context(|| format!("binding {listen}"))?;
    events::emit("hub_started", json!({"listen": listen, "version": crate::VERSION}));
    eprintln!("midas hub {}: answering on {listen}, state in {}", crate::VERSION, registry::root().display());
    std::thread::spawn(watch_heartbeats);
    std::thread::spawn(crate::push::watch);
    std::thread::spawn(crate::watch::run);
    std::thread::spawn(crate::runners::watch);
    for conn in listener.incoming() {
        // Out of descriptors, accept fails at once each time: a pause, not a spin.
        let Ok(mut stream) = conn else {
            std::thread::sleep(Duration::from_millis(50));
            continue;
        };
        // A connection is a thread, and a thread a task under the unit's TasksMax (256), which the
        // git and curl the hub runs count against too. `thread::spawn` panics when it cannot get one,
        // and with panic = "abort" that ended the hub (2026-10-27): turn away what is over the limit,
        // and drop what cannot get a thread, rather than everyone with it.
        if ANSWERING.fetch_add(1, Ordering::SeqCst) >= MAX_ANSWERING {
            ANSWERING.fetch_sub(1, Ordering::SeqCst);
            let _ = stream.set_write_timeout(Some(Duration::from_secs(1)));
            let _ = stream.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nRetry-After: 2\r\nConnection: close\r\n\r\n");
            continue;
        }
        let spawned = std::thread::Builder::new().spawn(move || {
            struct Done;
            impl Drop for Done {
                fn drop(&mut self) {
                    ANSWERING.fetch_sub(1, Ordering::SeqCst);
                }
            }
            let _done = Done;
            let peer = stream.peer_addr().map(|a| a.ip().to_string()).unwrap_or_default();
            if let Err(e) = handle(stream, &peer) {
                // A caller that went before its answer (a page closed, a stream cut) is no fault of the
                // hub's: logged, it buried the log's real errors under hundreds of broken pipes a day.
                let gone = e.chain().any(|c| {
                    c.downcast_ref::<std::io::Error>()
                        .is_some_and(|io| matches!(io.kind(), std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset))
                });
                if !gone {
                    events::emit("error", json!({"what": format!("hub request from {peer}: {e:#}")}));
                }
            }
        });
        if let Err(e) = spawned {
            // The closure, and the connection in it, is dropped unrun: the caller sees it closed.
            ANSWERING.fetch_sub(1, Ordering::SeqCst);
            events::emit("error", json!({"what": format!("no thread for a connection ({} open): {e}", ANSWERING.load(Ordering::SeqCst))}));
            std::thread::sleep(Duration::from_millis(100));
        }
    }
    Ok(0)
}

/// A `since` (seconds back) from a query: 30 days unless said, and never more than ten years,
/// which a reader's chrono arithmetic panicked past (with panic = "abort", the hub with it).
fn since_q(v: Option<String>) -> i64 {
    v.and_then(|v| v.parse::<i64>().ok()).unwrap_or(30 * 86400).clamp(0, 10 * 365 * 86400)
}

/// What lies between `prefix` and `suffix` in a path, or "" when it is not one of them.
/// Sliced by hand it panicked on `hosted/log` (prefix and suffix overlapping), and one
/// unauthenticated GET aborted the hub.
fn inner<'a>(p: &'a str, prefix: &str, suffix: &str) -> &'a str {
    p.strip_prefix(prefix).and_then(|r| r.strip_suffix(suffix)).unwrap_or("")
}

/// Connections being answered. Each holds a thread (a board stream two), and long polls hold
/// theirs for up to two minutes; what is left of TasksMax is the subprocesses'.
static ANSWERING: AtomicUsize = AtomicUsize::new(0);
const MAX_ANSWERING: usize = 160;

/// The most a request line or header line may be, how many headers, and how long they may take
/// to arrive. Unbounded, one line without a newline grew until the unit's memory limit, and a
/// caller sending a byte every nine seconds (under the read timeout) held a thread for good.
const MAX_LINE: u64 = 16 * 1024;
const MAX_HEADERS: usize = 100;
const HEAD_WITHIN: Duration = Duration::from_secs(30);

/// One line of a request's head, at most [`MAX_LINE`] long.
fn head_line(reader: &mut impl BufRead, line: &mut String) -> Result<usize> {
    let n = reader.by_ref().take(MAX_LINE).read_line(line)?;
    if n as u64 == MAX_LINE && !line.ends_with('\n') {
        bail!("a request line over {MAX_LINE} bytes");
    }
    Ok(n)
}

pub(crate) fn handle(mut stream: TcpStream, peer: &str) -> Result<()> {
    stream.set_read_timeout(Some(Duration::from_secs(10)))?;
    // A caller that stops reading would hold the thread as long as one that stops sending.
    stream.set_write_timeout(Some(Duration::from_secs(30)))?;
    let began = std::time::Instant::now();
    let mut reader = BufReader::new(stream.try_clone()?);
    let mut line = String::new();
    head_line(&mut reader, &mut line)?;
    let mut parts = line.split_whitespace();
    let (method, target) = (parts.next().unwrap_or("").to_string(), parts.next().unwrap_or("").to_string());
    let mut len = 0usize;
    let mut bearer = String::new();
    let mut key = String::new();
    let (mut cookie, mut origin, mut fwd_for, mut fwd_proto, mut fwd_host) =
        (String::new(), String::new(), String::new(), String::new(), String::new());
    let (mut upgrade, mut ws_key, mut ws_ext) = (String::new(), String::new(), String::new());
    // A paired device's token (device.rs): its own header, because Caddy strips `Authorization`.
    let mut device_token = String::new();
    // A session's media: its name and caption on the way in, a range on the way out.
    let (mut media_name, mut media_caption, mut media_tech, mut range) = (String::new(), String::new(), String::new(), String::new());
    // The page's own files: what the browser has already, and whether it takes gzip.
    let (mut if_none_match, mut gzip_ok) = (String::new(), false);
    // A git client's, for a public repository's smart HTTP (`public_git`).
    let (mut content_type, mut git_protocol, mut content_encoding) = (String::new(), String::new(), String::new());
    // The address the caller reached the hub at. Not always the hub's own: a Mac
    // node's VM comes through its machine's forwarder, at the VM's gateway.
    let mut host = String::new();
    for n in 0.. {
        if n == MAX_HEADERS || began.elapsed() > HEAD_WITHIN {
            bail!("a request's head too long or too slow ({n} headers in {:?})", began.elapsed());
        }
        let mut h = String::new();
        if head_line(&mut reader, &mut h)? == 0 || h == "\r\n" || h == "\n" {
            break;
        }
        let lower = h.to_ascii_lowercase();
        if let Some(v) = lower.strip_prefix("content-length:") {
            len = v.trim().parse().unwrap_or(0);
        }
        if let Some(v) = lower.strip_prefix("host:") {
            host = v.trim().to_string();
        }
        if lower.starts_with("authorization:") {
            bearer = h["authorization:".len()..].trim().trim_start_matches("Bearer").trim().to_string();
        }
        // The web page's caller key: behind a proxy that asks for a password,
        // `Authorization` is the browser's, so the page sends its key here.
        if lower.starts_with("x-midas-key:") {
            key = h["x-midas-key:".len()..].trim().to_string();
        }
        // The login session's cookie, and what says the request came through
        // the web proxy (Caddy adds X-Forwarded-*), and from which page.
        let value = || h[h.find(':').map_or(h.len(), |i| i + 1)..].trim().to_string();
        if lower.starts_with("cookie:") {
            cookie = value();
        } else if lower.starts_with("origin:") {
            origin = value();
        } else if lower.starts_with("x-forwarded-for:") {
            fwd_for = value();
        } else if lower.starts_with("x-forwarded-proto:") {
            fwd_proto = value().to_ascii_lowercase();
        } else if lower.starts_with("x-forwarded-host:") {
            fwd_host = value();
        } else if lower.starts_with("content-type:") {
            content_type = value();
        } else if lower.starts_with("git-protocol:") {
            git_protocol = value();
        } else if lower.starts_with("content-encoding:") {
            content_encoding = value();
        } else if lower.starts_with("upgrade:") {
            upgrade = value().to_ascii_lowercase();
        } else if lower.starts_with("sec-websocket-key:") {
            ws_key = value();
        } else if lower.starts_with("sec-websocket-extensions:") {
            ws_ext = value().to_ascii_lowercase();
        } else if lower.starts_with("x-midas-device:") {
            device_token = value();
        } else if lower.starts_with("x-midas-name:") {
            media_name = pct_decode(&value());
        } else if lower.starts_with("x-midas-caption:") {
            media_caption = pct_decode(&value());
        } else if lower.starts_with("x-midas-tech:") {
            media_tech = pct_decode(&value());
        } else if lower.starts_with("range:") {
            range = value();
        } else if lower.starts_with("if-none-match:") {
            if_none_match = value();
        } else if let Some(v) = lower.strip_prefix("accept-encoding:") {
            gzip_ok = v.split(',').any(|e| e.split(';').next().unwrap_or("").trim() == "gzip");
        }
    }
    if !key.is_empty() {
        bearer = key;
    }
    let who = Who::new(&bearer, &cookie, &origin, &fwd_for, &fwd_proto, if fwd_host.is_empty() { &host } else { &fwd_host }, peer);
    // The board, live (ws.rs). Reading, so open on the tunnel and a login's
    // through the web; and a browser sends its cookie to a WebSocket from any
    // page, so only this page's own may open one.
    if target == "/v1/stream" {
        if upgrade != "websocket" || ws_key.is_empty() {
            return respond(&mut stream, 400, "text/plain", b"a WebSocket, please");
        }
        if who.web && who.principal.is_none() {
            return respond(&mut stream, 401, "application/json", br#"{"error":"log in first","login":true}"#);
        }
        if !who.origin_ok {
            return respond(&mut stream, 403, "text/plain", b"not from this page");
        }
        return crate::ws::serve(stream, reader, &ws_key, &ws_ext);
    }
    // A paired device's link (device.rs): its token, through the web proxy like everything a phone sends.
    if target == "/v1/device/link" {
        if upgrade != "websocket" || ws_key.is_empty() {
            return respond(&mut stream, 400, "text/plain", b"a WebSocket, please");
        }
        let Some((id, _)) = crate::device::by_token(&device_token) else {
            events::emit("refused", json!({"why": "no device token", "path": "device/link", "peer": who.peer}));
            return respond(&mut stream, 401, "application/json", br#"{"error":"not a paired device: pair it again"}"#);
        };
        return crate::device::serve_link(stream, reader, &ws_key, &id);
    }
    // A public repository the hub hosts, to anyone (hosted.rs): clone, archive,
    // LFS and pages to read it by, at `/<owner>/<name>…` as Forgejo had them, so
    // its old links and `Cargo.toml`s still land. A private one is not found, as
    // one that is not there. `/git/…`, where they were first, still clones; a
    // page there is sent to its new path.
    let at_git = target.strip_prefix("/git/");
    if let Some(rest) = at_git.or_else(|| hosted_path(&target)) {
        let repo_seg = rest.split(['/', '?']).nth(1).unwrap_or("");
        if at_git.is_some() && method == "GET" && !repo_seg.ends_with(".git") {
            write!(stream, "HTTP/1.1 301 Moved Permanently\r\nLocation: /{rest}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")?;
            return Ok(());
        }
        let shown_host = if fwd_host.is_empty() { host.clone() } else { fwd_host.clone() };
        let g = PublicGit { method: &method, rest, len, content_type: &content_type, git_protocol: &git_protocol, host: &shown_host,
                            content_encoding: &content_encoding, peer, https: who.https };
        return public_git(&mut stream, &mut reader, &g);
    }
    // The site's front page, for a visitor the hub does not know: the public
    // repositories, and the way in. A person logged in, and the tunnel, get the page.
    if method == "GET" && target == "/" && who.web && who.principal.is_none() {
        let shown_host = if fwd_host.is_empty() { host.clone() } else { fwd_host.clone() };
        return respond(&mut stream, 200, "text/html; charset=utf-8", crate::codeview::front(&shown_host).as_bytes());
    }
    // Machines' paths are never a person's: not through the web proxy.
    if who.web && (target.starts_with("/lfs/") || target.starts_with("/v1/forgejo")) {
        return respond(&mut stream, 403, "text/plain", b"not through the web");
    }
    // LFS for nodes (mirror.rs), with the token `midas hub git` issued.
    if let Some(rest) = target.strip_prefix("/lfs/") {
        return lfs(&mut stream, &mut reader, &method, rest, len, &bearer, peer, &host);
    }
    if let Some(rest) = target.strip_prefix("/v1/forgejo") {
        return forgejo_proxy(&mut stream, &mut reader, &method, rest, len, &bearer, peer);
    }
    let (path, query) = target.split_once('?').unwrap_or((&target, ""));
    // An image a person pasted, ahead of the message it goes with: bytes, not
    // JSON. Pasting is steering, so it takes the steer role; and from a browser,
    // this page's own origin, as every change by cookie does.
    if method == "POST" && path == "/v1/uploads" {
        let may = who.principal.as_ref().is_some_and(|p| crate::accounts::at_least(&p.role, "steer")
            && (p.account.is_none() || who.origin_ok));
        if !may {
            return respond(&mut stream, 403, "application/json", br#"{"error":"pasting an image takes the steer role"}"#);
        }
        if len > crate::sessions::UPLOAD_MAX {
            return respond(&mut stream, 413, "application/json", br#"{"error":"an image of at most 10 MB"}"#);
        }
        let mut buf = vec![0u8; len];
        reader.read_exact(&mut buf)?;
        return match crate::sessions::upload(&media_name, &buf) {
            Ok(token) => respond(&mut stream, 200, "application/json", json!({"token": token}).to_string().as_bytes()),
            Err(e) => respond(&mut stream, 400, "application/json", json!({"error": format!("{e:#}")}).to_string().as_bytes()),
        };
    }
    // A tech's mockup as the scout photographed it (tree.rs, Sketch): a picture, read as the tree is.
    if let (true, Some(id)) = (method == "GET", path.strip_prefix("/v1/hosted/tree/mockups/")) {
        if who.web && who.principal.is_none() {
            return respond(&mut stream, 401, "application/json", br#"{"error":"log in first","login":true}"#);
        }
        return match crate::tree::mockup_png_path(id.trim_end_matches(".png")).filter(|p| p.exists()) {
            Some(p) => media_get(&mut stream, &p, ""),
            None => respond(&mut stream, 404, "application/json", br#"{"error":"no such mockup"}"#),
        };
    }
    // A hosted repository at `rev` as a .tar.gz, for the workspace (the project page's Download): a
    // private one too, so a login, as the tree's pictures take. A public one is also at `/<o>/<n>/archive/`.
    if let (true, Some(rest)) = (method == "GET", path.strip_prefix("/v1/repos/").and_then(|r| r.strip_suffix("/archive.tar.gz"))) {
        if who.principal.is_none() {
            return respond(&mut stream, 401, "application/json", br#"{"error":"log in first","login":true}"#);
        }
        let rev = query.split('&').find_map(|p| p.strip_prefix("rev=")).map(pct_decode).unwrap_or_else(|| "HEAD".into());
        return match crate::mirror::repo_name(rest).ok().filter(|r| crate::hosted::is_hosted(r)) {
            Some(repo) => archive(&mut stream, &repo, &rev),
            None => respond(&mut stream, 404, "application/json", br#"{"error":"no such project"}"#),
        };
    }
    // A picture of a tech as it really works (tree.rs, `add_shot`): `<tech>/<n>`, read as the tree is.
    if let (true, Some(rest)) = (method == "GET", path.strip_prefix("/v1/hosted/tree/shots/")) {
        if who.web && who.principal.is_none() {
            return respond(&mut stream, 401, "application/json", br#"{"error":"log in first","login":true}"#);
        }
        let found = rest.split_once('/').and_then(|(t, n)| crate::tree::shot_path(t, n.split('.').next().unwrap_or(""))).filter(|p| p.exists());
        return match found {
            Some(p) => media_get(&mut stream, &p, ""),
            None => respond(&mut stream, 404, "application/json", br#"{"error":"no such picture"}"#),
        };
    }
    // What a session shows the person (sessions.rs, media): bytes, not JSON.
    if let Some((id, tail)) = path.strip_prefix("/v1/hosted/").and_then(|r| r.split_once('/')) {
        if method == "POST" && tail == "media" {
            // From the session's machine, with a key that may steer: never a page.
            let may = !who.web && who.principal.as_ref().is_some_and(|p| crate::accounts::at_least(&p.role, "steer"));
            if !may {
                return respond(&mut stream, 403, "application/json", br#"{"error":"media comes from a session's machine, with a key of role steer"}"#);
            }
            if len > crate::sessions::MEDIA_MAX {
                return respond(&mut stream, 413, "application/json", br#"{"error":"too large to show"}"#);
            }
            let mut buf = vec![0u8; len];
            reader.read_exact(&mut buf)?;
            let caption = Some(media_caption.as_str()).filter(|c| !c.is_empty());
            // A picture of a tech as it really works (`midas show --tech`): kept on its card too.
            let kept = match crate::sessions::add_media(id, &media_name, caption, &buf) {
                Ok(file) if !media_tech.is_empty() => crate::tree::add_shot(&media_tech, id, &file, caption, &buf).map(|_| file),
                r => r,
            };
            return match kept {
                Ok(file) => respond(&mut stream, 200, "application/json", json!({"file": file}).to_string().as_bytes()),
                Err(e) => respond(&mut stream, 400, "application/json", json!({"error": format!("{e:#}")}).to_string().as_bytes()),
            };
        }
        // A session's agent's transcript, carried between machines (sessions.rs,
        // `handed`): from and to the machines that run it, never a page.
        if tail == "transcript" {
            let may = !who.web && who.principal.as_ref().is_some_and(|p| crate::accounts::at_least(&p.role, "steer"));
            if !may {
                return respond(&mut stream, 403, "application/json", br#"{"error":"a transcript is for a session's machines, with a key of role steer"}"#);
            }
            if method == "POST" {
                if len > crate::sessions::TRANSCRIPT_MAX {
                    return respond(&mut stream, 413, "application/json", br#"{"error":"too large a transcript"}"#);
                }
                let mut buf = vec![0u8; len];
                reader.read_exact(&mut buf)?;
                return match crate::sessions::put_transcript(id, &buf) {
                    Ok(()) => respond(&mut stream, 200, "application/json", br#"{"ok":true}"#),
                    Err(e) => respond(&mut stream, 400, "application/json", json!({"error": format!("{e:#}")}).to_string().as_bytes()),
                };
            }
            return match crate::sessions::transcript_path(id) {
                Some(p) => media_get(&mut stream, &p, ""),
                None => respond(&mut stream, 404, "application/json", br#"{"error":"no transcript"}"#),
            };
        }
        if let (true, Some(file)) = (method == "GET", tail.strip_prefix("media/")) {
            if who.web && who.principal.is_none() {
                return respond(&mut stream, 401, "application/json", br#"{"error":"log in first","login":true}"#);
            }
            return match crate::sessions::media_path(id, file) {
                Some(p) => media_get(&mut stream, &p, &range),
                None => respond(&mut stream, 404, "text/plain", b"no such file"),
            };
        }
    }
    // The midas a node takes (`midas node update`): bytes, from the node's own
    // address only, never through the web.
    if let Some((node, platform)) = path.strip_prefix("/v1/nodes/").and_then(|r| r.split_once("/midas/")) {
        if method != "GET" || who.web {
            return respond(&mut stream, 403, "text/plain", b"nodes only");
        }
        if let Some((code, v)) = from_node(node, peer) {
            return respond(&mut stream, code, "application/json", v.to_string().as_bytes());
        }
        let Some(file) = node_binary(platform) else {
            return respond(&mut stream, 404, "text/plain", b"no midas of this build for that platform");
        };
        let mut f = std::fs::File::open(&file)?;
        let size = f.metadata()?.len();
        write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n")?;
        std::io::copy(&mut f, &mut stream)?;
        return Ok(());
    }
    if method == "GET" && !path.starts_with("/v1/") {
        let Some(a) = crate::web::asset(path) else {
            return respond(&mut stream, 404, "text/plain", b"not found");
        };
        // Still asked each time (the names are fixed, so a new build must show at the
        // next load), but answered with nothing when the browser has these bytes.
        if if_none_match.split(',').any(|t| t.trim().trim_start_matches("W/") == a.etag) {
            write!(stream, "HTTP/1.1 304 Not Modified\r\nETag: {}\r\nCache-Control: no-cache\r\nVary: Accept-Encoding\r\nConnection: close\r\n\r\n", a.etag)?;
            return Ok(());
        }
        let (body, encoding) = match a.gzip {
            Some(gz) if gzip_ok => (gz, "Content-Encoding: gzip\r\n"),
            _ => (a.body, ""),
        };
        write!(
            stream,
            // Not for search engines: the public repositories' pages are, and they share the host.
            "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\n{encoding}ETag: {}\r\nCache-Control: no-cache\r\nVary: Accept-Encoding\r\nX-Robots-Tag: noindex, nofollow\r\nConnection: close\r\n\r\n",
            a.ctype,
            body.len(),
            a.etag
        )?;
        stream.write_all(body)?;
        return Ok(());
    }
    // An import brings a conversation's log in parts of up to IMPORT_BODY.
    let max = if path.starts_with("/v1/hosted/") && path.ends_with("/import") { crate::sessions::IMPORT_BODY }
        else if path.starts_with("/v1/hosted/") && path.ends_with("/files") { crate::sessions::FILES_BODY }
        // A Sketch round brings its mockups' pictures (tree.rs): from a runner's machine, never a page.
        else if path == "/v1/hosted/runner/scouted" && !who.web { crate::tree::SCOUTED_BODY }
        else if path == "/v1/device/push" && crate::device::by_token(&device_token).is_some() { crate::device::PUSH_MAX }
        // A tool call may carry a file the device needs (a building model for
        // cartopolis's replace_building is ~0.5 MB): from a session's machine,
        // with a key that may steer, never a page.
        else if path == "/v1/devices/call" && !who.web && who.principal.as_ref().is_some_and(|p| crate::accounts::at_least(&p.role, "steer")) { crate::device::PUSH_MAX }
        // A page with its texts for a remote MCP server (remote.rs), on the same terms.
        else if path == "/v1/remotes/call" && !who.web && who.principal.as_ref().is_some_and(|p| crate::accounts::at_least(&p.role, "steer")) { crate::device::PUSH_MAX }
        else { MAX_BODY };
    let body: Value = if method == "POST" && len > 0 && len <= max {
        let mut buf = vec![0u8; len];
        reader.read_exact(&mut buf)?;
        serde_json::from_slice(&buf).unwrap_or(Value::Null)
    } else {
        Value::Null
    };
    // What a paired device does, with its own token and nothing else (device.rs).
    if let Some(r) = device_api(&method, path, &body, &device_token, &who) {
        let (status, out) = r.unwrap_or_else(|e| (400, json!({"error": format!("{e:#}")})));
        return respond(&mut stream, status, "application/json", out.to_string().as_bytes());
    }
    // Logging in and out, and setting an account up: they set the cookie.
    if let Some(r) = login_api(&method, path, &body, &who) {
        let (status, out, set_cookie) = r.unwrap_or_else(|e| (400, json!({"error": format!("{e:#}")}), None));
        return respond_with(&mut stream, status, "application/json", out.to_string().as_bytes(), set_cookie.as_deref());
    }
    let (status, out) = match api(&method, path, query, &body, &who, peer, &host) {
        Ok(r) => r,
        Err(e) => (400, json!({"error": format!("{e:#}")})),
    };
    let text = if status == 204 { String::new() } else { out.to_string() };
    respond(&mut stream, status, "application/json", text.as_bytes())
}

/// A query string's value as it was before the page escaped it (`%xx`, `+`).
fn unescape(v: &str) -> String {
    let b = v.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'+' => out.push(b' '),
            b'%' if i + 2 < b.len() => {
                match u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""), 16) {
                    Ok(c) => {
                        out.push(c);
                        i += 2;
                    }
                    Err(_) => out.push(b'%'),
                }
            }
            c => out.push(c),
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// The hub's API. Reading is open to anything that can reach the tunnel
/// address; changing the workspace needs a caller key; the node endpoints (renew,
/// readings, events) are keyed by the node a node is.
fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &str, host: &str) -> Result<(u16, Value)> {
    let q = |k: &str| query.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(str::to_string);
    let s = |k: &str| body[k].as_str().map(str::to_string);
    // A detached worktree is on no branch: it sends none, and a midas from
    // before 2026-10-21 sent "HEAD" (what `rev-parse --abbrev-ref` says there).
    let branch = || s("branch").filter(|b| !b.is_empty() && b != "HEAD");
    let Some(path) = path.strip_prefix("/v1/") else { return Ok((404, json!({"error": "no such endpoint"}))) };
    // Through the web, even reading takes a login: the reads include every
    // node's address and readings.
    if who.web && who.principal.is_none() && !matches!(path, "health" | "caller") {
        return Ok((401, json!({"error": "log in first", "login": true})));
    }
    // Reads, and what nodes send.
    match (method, path) {
        ("GET", "health") => return Ok((200, json!({"ok": true, "version": crate::VERSION, "recipe": crate::setup::recipe(),
            "disk_free": crate::util::disk_space(&registry::root()).map(|d| d.0)}))),
        // Which caller the key sent is, if any: the web page asks, because a
        // proxy in front of it may add the key for it (midas.cartopolis.org).
        ("GET", "caller") => return Ok((200, match &who.principal {
            Some(p) => json!({"caller": p.caller, "account": p.account, "role": p.role}),
            None => json!({"caller": null, "account": null, "role": null}),
        })),
        ("GET", "state") => {
            // With the hub's own address and build, for the page's network diagram,
            // and its state disk's free space, which nothing but the page watches.
            let mut st = registry::snapshot()?;
            st["hub"] = json!({"listen": crate::conf::hub().listen, "version": crate::VERSION,
                               "disk_free": crate::util::disk_space(&registry::root()).map(|d| d.0)});
            return Ok((200, st));
        }
        // Paired devices (device.rs), with the tools each announced: no tokens.
        ("GET", "devices") => return Ok((200, json!({"devices": crate::device::list()}))),
        // Remote MCP servers (remote.rs), with the tools each announced: no tokens.
        ("GET", "remotes") => return Ok((200, crate::remote::list())),
        ("GET", p) if p.starts_with("devices/") => return Ok(match crate::device::get(&p["devices/".len()..]) {
            Some(d) => (200, d),
            None => (404, json!({"error": "no such device"})),
        }),
        ("GET", "events") => return Ok((200, json!(events::read_at(&registry::root(), &events::Filter::from_query(query))))),
        ("GET", "position") => return Ok((200, json!(registry::position(&q("owner").unwrap_or_default())?))),
        ("GET", "faster") => return Ok((200, json!({"node": registry::faster_free(&pct_decode(&q("owner").unwrap_or_default()),
            &pct_decode(&q("machine").unwrap_or_else(|| "any".into())), &pct_decode(&q("than").unwrap_or_default()),
            q("rank").map(|r| pct_decode(&r)).as_deref())?}))),
        ("GET", p) if p.starts_with("lease/") => return Ok((200, lease(&p["lease/".len()..])?)),
        // Notifications (push.rs): the key a browser subscribes with, and what waits now, for its service worker.
        ("GET", "push/key") => return Ok((200, json!({"key": crate::push::public_key()?}))),
        ("GET", "push/needs") => return Ok((200, json!(crate::push::needs()))),
        ("GET", "push/ntfy") => return Ok((200, json!({"topic": who.principal.as_ref().and_then(|p| p.account.as_deref()).and_then(crate::push::ntfy_of)}))),
        ("GET", "deploys") => {
            let mut o = crate::deploy::overview();
            // What follows landings, per project: its tip, a hold, and what each target's next deploy waits for.
            o["ships"] = json!(crate::ship::plans());
            // The deploys going now, step by step: how far each is, and what each step takes as a rule.
            o["running"] = json!(crate::deploy::running());
            return Ok((200, o));
        }
        // A project's part of the shared skills (hub.conf `projects`).
        ("GET", "project") => return Ok(match crate::conf::hub().project(&q("repo").unwrap_or_default()) {
            Some(p) => (200, p),
            None => (404, json!({"error": "the hub does not mirror that repository (hub.conf `repos`)"})),
        }),
        ("GET", p) if p.starts_with("deploys/") => return Ok((200, crate::deploy::status(&p["deploys/".len()..])?)),
        ("GET", "history") => {
            let since = since_q(q("since"));
            let mut h = crate::builds::history(since);
            // Each node's held and busy time (at most a week of it), for the Workspace page.
            if q("use").as_deref() == Some("1") {
                h["use"] = json!(crate::stats::node_use_now(since));
            }
            return Ok((200, h));
        }
        // What each deployed target's service did (watch.rs): its samples by `step`, its state, and the deploys among them.
        ("GET", "watch") => {
            let since = q("since").and_then(|s| s.parse::<i64>().ok()).unwrap_or(6 * 3600);
            let step = q("step").and_then(|s| s.parse::<i64>().ok());
            return Ok((200, crate::watch::read(since, step)));
        }
        // What each node used over time (usage.rs): memory, load and disk per `step` seconds.
        ("GET", "usage") => {
            let since = since_q(q("since")).min(crate::usage::KEEP_DAYS * 86400);
            let step = q("step").and_then(|s| s.parse::<i64>().ok());
            return Ok((200, crate::usage::read(since, step)));
        }
        // What each machine drew (power.rs): average watts and watt-hours per `step` seconds.
        ("GET", "power") => {
            let since = q("since").and_then(|s| s.parse::<i64>().ok()).unwrap_or(86400);
            let step = q("step").and_then(|s| s.parse::<i64>().ok());
            return Ok((200, crate::power::read(since, step)));
        }
        ("GET", "builds") => {
            let since = since_q(q("since"));
            return Ok((200, json!(crate::builds::read(since))));
        }
        ("GET", "names") => return Ok((200, crate::collab::names())),
        // How many notes wait for a session: what its commands say, while only
        // its hooks hand them over (collab.rs).
        ("GET", "notes/count") => return Ok((200, json!({"count": crate::collab::count_notes(&q("owner").unwrap_or_default())}))),
        ("GET", "reservations") => return Ok((200, crate::collab::reservations())),
        ("GET", "todos") => return Ok((200, crate::collab::todos())),
        ("GET", "decisions") => return Ok((200, crate::collab::decisions())),
        // Admin windows (admin.rs): how they stand, and the grant the page is to sign for one.
        ("GET", "admin") => return Ok((200, crate::admin::status())),
        ("GET", "admin/sign") => return Ok(match crate::admin::to_sign(&q("id").unwrap_or_default()) {
            Ok(v) => (200, v),
            Err(e) => (409, json!({"error": format!("{e:#}")})),
        }),
        // The person's decision load, limits, rules and the autopilot's answers for them (focus.rs):
        // the logged-in person's, else the one who decided last. The page says its clock's offset.
        ("GET", "focus") => {
            let person = who.principal.as_ref().and_then(|p| p.account.clone()).unwrap_or_else(crate::focus::default_person);
            if let Some(tz) = q("tz").and_then(|t| t.parse().ok()) {
                crate::focus::seen_tz(&person, tz);
            }
            return Ok((200, crate::focus::overview(&person)));
        }
        // What the autopilot reads of the person when it decides in a session: their rules, earlier answers, cap.
        ("GET", "focus/pilot") => return Ok((200, crate::focus::pilot_context(&q("session").unwrap_or_default())?)),
        ("GET", "hosted") => return Ok((200, crate::sessions::list())),
        // Goals ▸ Map: every project, which uses which, and the sessions between them (graph.rs), drawn.
        ("GET", "hosted/graph") => {
            let g = crate::graph::all();
            let svg = crate::graph::svg(&g, None);
            return Ok((200, json!({"graph": g, "svg": svg})));
        }
        // The sessions runners: each now, and their starts, stops and absences (runners.rs).
        ("GET", "runners") => return Ok((200, crate::runners::read(since_q(q("since"))))),
        ("GET", "hosted/search") => {
            let limit = q("limit").and_then(|l| l.parse().ok()).unwrap_or(50).min(200);
            return Ok((200, crate::sessions::search(&unescape(&q("q").unwrap_or_default()), limit)));
        }
        // What every session's conversation holds, counted (the History page's Conversations).
        ("GET", "hosted/stats") => {
            let since = since_q(q("since"));
            return Ok((200, crate::sessions::stats(since)));
        }
        // Whether the page may offer to talk a session over (discuss.rs).
        ("GET", "hosted/projects") => return Ok((200, crate::sessions::projects())),
        // A repository the hub hosts, read without a checkout (hosted.rs):
        // repos/<owner>/<name>/{show,log,branches,commit}.
        ("GET", p) if p.starts_with("repos/") => return repo_read(&p["repos/".len()..], &q),
        // Templates and their schedules (templates.rs), for the page's Autopilot.
        ("GET", "hosted/templates") => return Ok((200, crate::templates::all())),
        // The research tree: goals, techs, insights and the scout's rounds (tree.rs).
        ("GET", "hosted/tree") => return Ok((200, crate::tree::all())),
        // The agents a session may be started with (Settings ▸ Agents, and Claude Code): ids and names.
        ("GET", "hosted/agents") => return Ok((200, crate::agents::list(false))),
        ("GET", "hosted/discuss") => return Ok((200, json!({"available": crate::discuss::available()}))),
        // Voice conversations kept, newest first, and one whole (talks.rs).
        ("GET", "hosted/talks") => return Ok((200, crate::talks::list())),
        ("GET", p) if p.starts_with("hosted/talks/") => return Ok((200, crate::talks::get(&p["hosted/talks/".len()..])?)),
        // The hub's settings that the page sets (Settings): of the OpenAI key, only whether there is one.
        ("GET", "settings") => return Ok((200, json!({"discuss": crate::discuss::overview()}))),
        ("GET", p) if !inner(p, "hosted/", "/log").is_empty() => {
            let id = inner(p, "hosted/", "/log");
            return Ok((200, crate::sessions::log(id, q("after").and_then(|a| a.parse().ok()).unwrap_or(0))?));
        }
        // What a session's branch changes (sessions.rs `report_files`): the page's Files.
        ("GET", p) if !inner(p, "hosted/", "/files").is_empty() => {
            return Ok((200, crate::sessions::files(inner(p, "hosted/", "/files"))?));
        }
        ("GET", p) if p.starts_with("hosted/") && p != "hosted/runner/poll" => return Ok((200, crate::sessions::meta(&p["hosted/".len()..])?)),
        ("GET", "landings") => {
            let since = since_q(q("since"));
            return Ok((200, json!(crate::builds::landings(since))));
        }
        ("GET", "sessions") => {
            let since = since_q(q("since"));
            return Ok((200, json!(crate::builds::sessions(since))));
        }
        // A node renews its own node's lease on every session: builds on a node
        // never pass through anything else that could.
        ("POST", p) if p.starts_with("renew/") => {
            if let Some(refused) = from_node(&p["renew/".len()..], peer) { return Ok(refused); }
            let r = registry::renew(None, Some(&p["renew/".len()..]), body["command"].as_str())?;
            return Ok((200, json!({"renewed": r.is_some()})));
        }
        ("POST", "events") => {
            let mut ev = body.clone();
            if ev.is_object() {
                // A kind the hub acts on is taken only from a caller key, or from
                // the node it names: anything on the tunnel can post a line, and
                // one that released another session's lease, ended a session or
                // counted a deploy as published must not be one of them.
                let kind = ev["kind"].as_str().unwrap_or("");
                if events::drives_state(kind) && who.principal.is_none() {
                    let node = ev["node"].as_str().unwrap_or("");
                    if kind != "ssh_session" || node.is_empty() {
                        return Ok((403, json!({"error": format!("a {kind} event is taken only from a caller key")})));
                    }
                    if let Some(refused) = from_node(node, peer) { return Ok(refused); }
                }
                ev["via_hub_from"] = json!(peer);
                events::record(&ev);
                // A command the node stopped for doing nothing (stall.rs): its
                // session is told by a note too, which wakes it when idle —
                // the ssh ending tells an agent that ran it in the background,
                // but not one whose ssh was gone already. Only from the node.
                let node = ev["node"].as_str().unwrap_or("");
                if ev["kind"] == "stalled" && ev["stage"] == "stop" && !node.is_empty() && from_node(node, peer).is_none() {
                    if let Some(actor) = ev["actor"].as_str().filter(|a| !a.is_empty()) {
                        let _ = crate::collab::say("hub", actor, &crate::stall::note_stop(&ev), "stalled");
                    }
                }
            }
            return Ok((204, Value::Null));
        }
        // The secrets a bot on a node starts with — the hub's for the node
        // (`midas bot token`), and with `bot` that bot's own on top (Settings ▸
        // Bots; the more particular wins) — to the node itself and nobody else.
        // Only the node's holder can run anything there, so only the holder
        // comes by them; until 2026-11-21 any caller key read any node's.
        ("POST", "bot/secrets/for") => {
            let node = s("node").unwrap_or_default();
            if let Some(refused) = from_node(&node, peer) { return Ok(refused); }
            let mut env = crate::botsecrets::for_node(&node);
            let bot = s("bot").filter(|b| !b.is_empty());
            if let Some(b) = &bot {
                env.extend(crate::botconfig::env_for(b));
            }
            events::emit("bot_secrets_read", json!({
                "node": node, "bot": bot, "names": env.keys().collect::<Vec<_>>(),
                "holder": registry::snapshot().ok().and_then(|st| st["leases"][&node]["owner"].as_str().map(str::to_string)),
            }));
            return Ok((200, json!({"env": env})));
        }
        // A node's heartbeat: its latest reading, one file per node.
        ("POST", p) if p.starts_with("readings/") => {
            let node = &p["readings/".len()..];
            if let Some(refused) = from_node(node, peer) { return Ok(refused); }
            if !body.is_object() || !registry::is_node(node) {
                return Ok((400, json!({"error": "not a reading for a known node"})));
            }
            let mut v = body.clone();
            v["at"] = json!(registry::now());
            v["from"] = json!(peer);
            registry::write_reading(node, &v)?;
            // Kept over time too; a failed append loses a minute, not the heartbeat.
            let _ = crate::usage::record(node, &v);
            registry::note_hub_url(node, host)?;
            // A session open on the node keeps its lease alive: that is what
            // "in use" means, and a long build has no other way to say so. So
            // does a bot lease's running bot, which has no session open at all.
            registry::renew_if_in_use(node, body)?;
            return Ok((204, Value::Null));
        }
        // A machine's power, from its own address: the one its nodes have.
        ("POST", "power") => return crate::power::record(peer, body),
        // A machine's VMs, and which of them to keep running (sleep.rs).
        ("POST", "sleep") => return crate::sleep::host(peer, body),
        // What a node being set up needs to know about itself. All of it is
        // public: where it listens, and which public keys may log into it.
        ("GET", p) if !inner(p, "nodes/", "/config").is_empty() => {
            let node = inner(p, "nodes/", "/config");
            let Some(n) = registry::nodes().into_iter().find(|n| n["id"] == node) else {
                return Ok((404, json!({"error": format!("no node {node} — add it first: midas nodes add {node} …")})));
            };
            let conf = crate::conf::hub();
            let operator = std::fs::read_to_string(format!("{}.pub", crate::hubsetup::OPERATOR_KEY)).unwrap_or_default();
            let mut keys: Vec<String> = conf.agent_keys.clone();
            let operator_keys: Vec<String> = registry::ed25519_key(&operator).into_iter().collect();
            keys.retain(|k| !operator_keys.contains(k));
            // The uuid is what the machine keeps the node's data under, and the
            // former names are how it finds a node it runs under an old one.
            return Ok((200, json!({
                "node": node, "uuid": registry::uuid_of(node), "former_names": n["former_names"],
                "address": n["address"], "port": n["ssh_port"], "gpu": n["gpu"],
                "hub": conf.url(), "repo": conf.repos.first(), "agent_keys": keys, "operator_keys": operator_keys,
            })));
        }
        // Which midas a node should run (`midas node update`): this hub's
        // build, if the hub has it for the node's platform, and whether the
        // node is held — it changes only while free.
        ("GET", p) if !inner(p, "nodes/", "/midas").is_empty() => {
            let node = inner(p, "nodes/", "/midas");
            if let Some(refused) = from_node(node, peer) { return Ok(refused); }
            let platform = q("platform").unwrap_or_default();
            let build = node_binary(&platform).map(|_| crate::VERSION);
            let held = lease(node)?["leased"] == true;
            return Ok((200, json!({"build": build, "held": held})));
        }
        ("POST", p) if !inner(p, "nodes/", "/register").is_empty() => {
            let node = inner(p, "nodes/", "/register");
            if registry::register_node(node, peer, &s("git_key").unwrap_or_default(), &s("host_key").unwrap_or_default())? {
                crate::hubsetup::refresh_ssh()?;
            }
            registry::note_hub_url(node, host)?;
            return Ok((200, json!({"ok": true})));
        }
        // The git server's post-receive hook, on this machine: a branch moved.
        // Accepted only from the hub's own address, which only something on
        // this machine can speak from — it needs no key, because all it can do
        // is make the hub fetch a little sooner than it would have.
        ("POST", "pushed") => {
            if !from_this_machine(peer) {
                events::emit("refused", json!({"why": "a push note from another machine", "peer": peer}));
                return Ok((403, json!({"error": "push notes come from the git server on the hub's own machine"})));
            }
            let repo = crate::mirror::repo_name(&s("repo").unwrap_or_default())?;
            for line in body["refs"].as_array().into_iter().flatten() {
                let f = |k: &str| line[k].as_str().unwrap_or("").to_string();
                registry::note_push(&repo, &f("ref"), &f("old"), &f("new"))?;
            }
            // In the background: the hook is waiting on this answer, and the
            // push it reports is waiting on the hook.
            if crate::conf::hub().allows(&repo) {
                crate::util::spawn_detached("a fetch after a push", move || {
                    if let Err(e) = crate::mirror::fetch_now(&repo) {
                        events::emit("error", json!({"what": format!("refreshing {repo} after a push: {e:#}")}));
                    }
                });
            }
            return Ok((204, Value::Null));
        }
        _ => {}
    }
    // Everything else changes the workspace, and needs a caller: a key, or a
    // person logged in with at least the role the change takes.
    let Some(p) = &who.principal else {
        events::emit("refused", json!({"why": "no caller key", "path": path, "peer": peer}));
        return Ok((401, json!({"error": "this changes the workspace and needs a caller key, or a login", "login": who.web})));
    };
    // Typing into an agent session is running code: steer.
    let needed = if path == "accounts" || path.starts_with("accounts/") || path.starts_with("settings/") { "admin" }
        else if path.starts_with("hosted/") || path.starts_with("devices/") || path.starts_with("remotes/") || path.starts_with("focus/") { "steer" } else { "operator" };
    // A runner is a machine: a key, never a person's login.
    let runner_path = path == "hosted/runner/poll" || path == "hosted/runner/bot" || path == "hosted/runner/agent" || path == "hosted/runner/answer" || path == "hosted/attach"
        || path == "hosted/runner/review" || path == "hosted/runner/scouted" || path == "hosted/runner/scouting"
        || (path.starts_with("hosted/") && (path.ends_with("/push") || path.ends_with("/handed") || path.ends_with("/handed_back") || path.ends_with("/files")));
    if runner_path && p.account.is_some() {
        return Ok((403, json!({"error": "for a runner's key"})));
    }
    if !crate::accounts::at_least(&p.role, needed) {
        events::emit("refused", json!({"why": format!("{} is {}, this takes {needed}", p.caller, p.role), "path": path, "peer": peer}));
        return Ok((403, json!({"error": format!("this takes the {needed} role; {} has {}", p.account.as_deref().unwrap_or(&p.caller), p.role)})));
    }
    // A cookie goes with every request the browser makes, a forged one too:
    // a change by cookie must come from the page itself.
    if p.account.is_some() && !who.origin_ok {
        events::emit("refused", json!({"why": "a change by cookie from another page", "path": path, "peer": peer}));
        return Ok((403, json!({"error": "not from this page"})));
    }
    let caller = p.caller.clone();
    // A person's changes are theirs, whatever the page says it is.
    let owner = p.account.clone().unwrap_or_else(|| s("owner").unwrap_or_default());
    // Who did it, for the record: `caller:owner`, or the caller alone.
    let by = if owner.is_empty() { caller.clone() } else { format!("{caller}:{owner}") };
    let ok = (200, json!({"ok": true}));
    Ok(match (method, path) {
        ("POST", "claim") => {
            let c = registry::Claim {
                owner, machine: s("machine").unwrap_or_else(|| "any".into()), node: s("node"),
                branch: branch(), purpose: s("purpose"),
                ttl: body["ttl"].as_i64().unwrap_or(registry::DEFAULT_TTL),
                queue: body["queue"].as_bool().unwrap_or(false),
                mode: registry::Mode::parse(body["mode"].as_str())?,
                rank: s("rank"),
            };
            match registry::claim(&c)? {
                Ok(node) => (200, node),
                Err(why) => (409, why),
            }
        }
        ("POST", "release") => match registry::release(&owner, s("node").as_deref(), body["force"] == true)? {
            Some(sid) => (200, json!({"node": sid})),
            None => (404, json!({"error": "nothing to release"})),
        },
        ("POST", "renew") => match registry::renew(Some(&owner), None, s("command").as_deref())? {
            Some(sid) => (200, json!({"node": sid})),
            None => (404, json!({"error": "you hold no node"})),
        },
        ("POST", "unqueue") => { registry::unqueue(&owner)?; ok }
        // Paired devices (device.rs). A code is a person's to make: the device becomes theirs.
        ("POST", "devices/code") => match &p.account {
            Some(a) => (200, crate::device::code(a, host)?),
            None => (403, json!({"error": "a person pairs a device, logged in to the page"})),
        },
        ("POST", "devices/forget") => { crate::device::forget(&s("id").unwrap_or_default(), &by)?; ok }
        // A session's call to a device: from the session's machine, with its key; never a page.
        ("POST", "devices/call") => {
            if p.account.is_some() || who.web {
                return Ok((403, json!({"error": "a device is called from a session's machine"})));
            }
            let id = s("device").unwrap_or_default();
            let wait = std::time::Duration::from_secs(body["timeout"].as_u64().unwrap_or(60));
            let r = crate::device::call(&id, &s("session").unwrap_or_default(), &body["request"], wait, &by)?;
            let name = crate::device::get(&id).map(|d| d["name"].clone()).unwrap_or(Value::Null);
            (200, json!({"response": r, "name": name}))
        }
        // A session's call to a remote MCP server (remote.rs), forwarded with the
        // hub's token: from a session's machine, never a page.
        ("POST", "remotes/call") => {
            if p.account.is_some() || who.web {
                return Ok((403, json!({"error": "a remote MCP server is called from a session's machine"})));
            }
            let caller = s("session").filter(|x| !x.is_empty()).unwrap_or_else(|| by.clone());
            (200, json!({"response": crate::remote::call(&s("name").unwrap_or_default(), &body["request"], &caller)?}))
        }
        // Sessions working together (collab.rs).
        // A name the hub does not know is refused with the closest it does
        // (404, `suggestions`); `re` answers a note's sender. `to` lists the
        // recipients, as it always has; `notes` says per recipient the note's
        // id and whether it woke an idle session or found one idle.
        ("POST", "say") => {
            // A person on the page talks to agents, which is steering, and speaks
            // as `web:<account>`: never as a session, whatever the page sends.
            if p.account.is_some() && !crate::accounts::at_least(&p.role, "steer") {
                return Ok((403, json!({"error": format!("a message to a session takes the steer role; {} has {}", owner, p.role)})));
            }
            let from = p.account.as_ref().map_or_else(|| owner.clone(), |a| format!("web:{a}"));
            match crate::collab::say_to(&from, &s("to").unwrap_or_default(), &s("text").unwrap_or_default(), s("re").as_deref()) {
                Ok(sent) => {
                    let to: Vec<Value> = sent.iter().map(|n| n["to"].clone()).collect();
                    (200, json!({"to": to, "notes": sent}))
                }
                Err(e) => match e.downcast_ref::<crate::collab::Unknown>() {
                    Some(u) => (404, json!({"error": u.error, "suggestions": u.suggestions})),
                    None => return Err(e),
                },
            }
        }
        ("POST", "notes/take") if body["peek"] == true => (200, json!({"notes": crate::collab::peek_notes(&owner)})),
        ("POST", "notes/take") if body["hold"] == true => (200, json!({"notes": crate::collab::hold_notes(&owner)?})),
        ("POST", "notes/take") => (200, json!({"notes": crate::collab::take_notes(&owner)?})),
        ("POST", "notes/confirm") => {
            let ids: Vec<String> = body["ids"].as_array().into_iter().flatten()
                .filter_map(|i| i.as_str().map(str::to_string)).take(1000).collect();
            (200, json!({"read": crate::collab::confirm_notes(&owner, &ids)?}))
        }
        ("POST", "notes/sent") => (200, json!({"sent": crate::collab::sent_by(&owner)})),
        ("POST", "work") => {
            let files: Vec<String> = body["files"].as_array().into_iter().flatten()
                .filter_map(|f| f.as_str().map(str::to_string)).take(5000).collect();
            let functions = crate::collab::functions_from(&body["functions"]);
            let projects: Option<Vec<String>> = body["projects"].as_array().map(|a| a.iter().filter_map(Value::as_str)
                .map(|p| p.rsplit('/').next().unwrap_or(p).to_string()).take(100).collect());
            (200, json!({"overlaps": crate::collab::report_work_in(&owner, branch().as_deref(), &files, functions.as_ref(),
                                                                   s("repo").as_deref(), projects.as_deref())?}))
        }
        ("POST", "editing") => {
            let files: Vec<String> = body["files"].as_array().into_iter().flatten()
                .filter_map(|f| f.as_str().map(str::to_string)).take(100).collect();
            let functions = crate::collab::functions_from(&body["functions"]);
            (200, json!({"overlaps": crate::collab::editing_with(&owner, branch().as_deref(), &files, functions.as_ref(), s("repo").as_deref())?}))
        }
        ("POST", "next") => {
            let node = s("node").unwrap_or_default();
            let why = s("why").filter(|w| !w.trim().is_empty()).unwrap_or_else(|| "needs it next".into());
            let holder = registry::reserve_next(&node, &owner, &why)?;
            if let Some(h) = &holder {
                crate::collab::say("hub", h, &format!(
                    "{owner} needs {node} next ({why}). Nothing changes for you: keep it as long as you need. \
                     When you `midas release`, it goes to them rather than to the queue; copy anything you \
                     want from the node's /tmp first."), "next")?;
            }
            (200, json!({"node": node, "holder": holder}))
        }
        ("GET", "accounts") => (200, crate::accounts::list()?),
        // Lists the account's models with the hub's OpenAI key: an admin's, as setting it is.
        ("GET", "settings/models") => (200, crate::discuss::models()?),
        ("POST", "accounts/add") => {
            let name = s("name").unwrap_or_default();
            let token = crate::accounts::add(&name, &s("role").unwrap_or_else(|| "operator".into()), &format!("{caller}:{owner}"))?;
            (200, json!({"name": name, "token": token}))
        }
        // A person does not demote, reset or remove their own account from the page: that is
        // how the last admin locks everyone out. Another admin, or the CLI's key, still can.
        ("POST", "accounts/role" | "accounts/reset" | "accounts/remove") if p.account.is_some() && p.account == s("name") =>
            (403, json!({"error": "not your own account: ask another admin, or use `midas account` with the hub's key"})),
        ("POST", "accounts/role") => {
            crate::accounts::set_role(&s("name").unwrap_or_default(), &s("role").unwrap_or_default(), &format!("{caller}:{owner}"))?;
            ok
        }
        ("POST", "accounts/reset") => {
            let name = s("name").unwrap_or_default();
            (200, json!({"name": name, "token": crate::accounts::reset(&name, &format!("{caller}:{owner}"))?}))
        }
        ("POST", "accounts/remove") => {
            crate::accounts::remove(&s("name").unwrap_or_default(), &format!("{caller}:{owner}"))?;
            ok
        }
        ("POST", "settings/discuss") => {
            crate::discuss::set_settings(&serde_json::from_value(body.clone()).context("not settings")?, &by)?;
            (200, json!({"discuss": crate::discuss::overview()}))
        }
        ("POST", "settings/openai_key") => {
            crate::discuss::set_key(&s("key").unwrap_or_default(), &by)?;
            (200, json!({"discuss": crate::discuss::overview()}))
        }
        // The bots' sign-ins and voice keys (botconfig.rs): names and whether
        // each secret is set, never a value.
        ("GET", "settings/bots") => (200, json!({"bots": crate::botconfig::overview()})),
        ("POST", "settings/bot") => {
            crate::botconfig::set(&s("name").unwrap_or_default(), body, &by)?;
            (200, json!({"bots": crate::botconfig::overview()}))
        }
        ("POST", "settings/bot/remove") => {
            crate::botconfig::remove(&s("name").unwrap_or_default(), &by)?;
            (200, json!({"bots": crate::botconfig::overview()}))
        }
        // The agents a session may run (agents.rs): a command run on the runner's machine, so admin only.
        ("GET", "settings/agents") => (200, crate::agents::list(true)),
        ("POST", "settings/agent") => {
            crate::agents::set(&s("id").unwrap_or_default(), &s("name").unwrap_or_default(), &s("command").unwrap_or_default(), &by)?;
            (200, crate::agents::list(true))
        }
        ("POST", "settings/agent/remove") => {
            crate::agents::remove(&s("id").unwrap_or_default(), &by)?;
            (200, crate::agents::list(true))
        }
        // Start or stop a configured bot: the sessions runner does it.
        ("POST", "settings/bot/start") | ("POST", "settings/bot/stop") => {
            let action = if path.ends_with("/start") { "start" } else { "stop" };
            crate::botconfig::request(&s("name").unwrap_or_default(), action, &by)?;
            (200, json!({"bots": crate::botconfig::overview()}))
        }
        // The runner says how a bot's start or stop went.
        ("POST", "hosted/runner/bot") => {
            crate::botconfig::report(&s("name").unwrap_or_default(), &s("state").unwrap_or_default(), &s("detail").unwrap_or_default())?;
            ok
        }
        // A repository's agent memory and the workspace's (memory.rs): a
        // caller's, as nodes are not to read what agents learnt about the machines.
        ("GET", "memory") => (200, match q("repo").filter(|r| !r.is_empty()) {
            Some(r) => crate::memory::read(&unescape(&r))?,
            // Without one: every set, for the page's Memory.
            None => crate::memory::read_all()?,
        }),
        ("POST", "memory") => {
            let changes: Vec<crate::memory::Change> = serde_json::from_value(body["changes"].clone()).context("not memory changes")?;
            (200, crate::memory::change(&s("repo").unwrap_or_default(), &changes, &by)?)
        }
        ("POST", "hosted/import") => (200, crate::sessions::import_begin(&by, body)?),
        // A session for tooling, by name and brief: 400 for what it cannot take, 409 for a clash.
        ("POST", "hosted/create") => {
            let made = crate::sessions::create(&by, &s("name").unwrap_or_default(), &s("brief").unwrap_or_default(), s("repo").as_deref(), s("base").as_deref())?;
            match made {
                Ok(v) => (200, v),
                Err(why @ crate::sessions::Refused::Invalid(_)) => (400, json!({"error": why.to_string(), "kind": "invalid"})),
                Err(why @ crate::sessions::Refused::Conflict(_)) => (409, json!({"error": why.to_string(), "kind": "conflict"})),
            }
        }
        ("POST", "hosted/start") => {
            let id = crate::sessions::start(&by, &s("prompt").unwrap_or_default(),s("repo").as_deref(), s("base").as_deref(), s("mode").as_deref(), s("model").as_deref(), s("agent").as_deref(), &body["images"])?;
            if let Some(from) = s("from") {
                crate::sessions::set_from(&id, &from)?;
            }
            (200, json!({"id": id}))
        }
        // A voice conversation about a session, signed with the hub's OpenAI key (discuss.rs).
        ("POST", "hosted/discuss") => {
            let tools: Vec<String> = body["tools"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(str::to_string)).collect();
            let (sdp, engine) = crate::discuss::open(&s("sdp").unwrap_or_default(), &s("instructions").unwrap_or_default(), &tools, &s("voice").unwrap_or_default())?;
            (200, json!({"sdp": sdp, "engine": engine}))
        }
        // A question about the code from a voice call, for a runner's Claude Code to answer (ask.rs).
        ("POST", "hosted/discuss/ask") => {
            (200, json!({"id": crate::ask::ask(&s("question").unwrap_or_default(), s("repo").as_deref(), s("session").as_deref(), &by)?}))
        }
        // Its answer, once there is one: a long poll.
        ("POST", "hosted/discuss/answer") => (200, crate::ask::wait(&s("id").unwrap_or_default(), 20)?),
        // A voice conversation saved as it goes, or forgotten (talks.rs).
        ("POST", "hosted/talks") => (200, crate::talks::save(body, &by)?),
        ("POST", "hosted/talks/forget") => {
            crate::talks::forget(&s("id").unwrap_or_default())?;
            ok
        }
        // A runner's review of a template's run (templates.rs).
        ("POST", "hosted/runner/review") => {
            crate::templates::reviewed(body)?;
            ok
        }
        // Templates and schedules changed, or a template started (templates.rs).
        ("POST", "hosted/templates") => (200, crate::templates::op(body, &by)?),
        // A scout's round on a goal of the research tree, as a runner found it (tree.rs).
        ("POST", "hosted/runner/scouted") => {
            crate::tree::scouted(body)?;
            ok
        }
        // What the scout reads while a round goes on, so the page can show it at work.
        ("POST", "hosted/runner/scouting") => {
            crate::tree::scouting(body)?;
            ok
        }
        // The research tree changed: a goal, an idea, a tech confirmed or dropped, a round asked for.
        ("POST", "hosted/tree") => (200, crate::tree::op(body, &by)?),
        // The autopilot on (or off) for many sessions at once: Take over (autopilot.rs).
        ("POST", "hosted/autopilot") => (200, crate::autopilot::take_over(body, &by)?),
        // The person's own focus (focus.rs): their limits and blocks, the rules the autopilot may use,
        // how the day felt, and an autopilot's answer taken back.
        ("POST", f) if f.starts_with("focus/") => {
            let person = p.account.clone().unwrap_or_else(crate::focus::default_person);
            match f {
                "focus/settings" => (200, crate::focus::set(&person, body)?),
                "focus/rules" => (200, json!({"rules": crate::focus::rule_op(body, &by)?})),
                "focus/checkin" => {
                    crate::focus::checkin(&person, body["rating"].as_i64().unwrap_or(0))?;
                    ok
                }
                "focus/undo" => {
                    crate::focus::undo(&person, &s("session").unwrap_or_default(), body["n"].as_u64().unwrap_or(0), &by)?;
                    ok
                }
                _ => (404, json!({"error": "no such endpoint"})),
            }
        }
        // A runner's answer to one.
        ("POST", "hosted/runner/answer") => {
            crate::ask::answered(&s("id").unwrap_or_default(), &s("answer").unwrap_or_default(), &s("error").unwrap_or_default())?;
            ok
        }
        ("POST", "hosted/runner/poll") => {
            // What it can do beyond sessions: a runner built before the research tree says nothing, and gets no rounds.
            let can: Vec<&str> = body["can"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
            let runner = s("runner").unwrap_or_else(|| caller.clone());
            // A runner of the hub's sessions, not an editor's mirror (`take: false`, tap.rs): seen to be there (runners.rs).
            if body["take"] != false {
                crate::runners::polled(&runner);
            }
            (200, crate::sessions::poll_with(&runner, &body["have"], body["take"] != false, &can)?)
        }
        // The command for a session's agent, for the runner starting it: a key's, never a person's login.
        ("POST", "hosted/runner/agent") => (200, json!({"command": crate::agents::command(&s("id").unwrap_or_default())?})),
        // A session finished on the person's answer (`land --finish`, `midas sessions finish`), by its owner name.
        ("POST", "hosted/finish") => {
            let id = crate::sessions::id_of_owner(&s("owner").unwrap_or_default())
                .context("only a session the hub runs (session-<id>) is finished this way")?;
            (200, json!({"said": crate::sessions::finish(&id, &by, s("sha").as_deref(), s("repo").as_deref(), body["drop"] == true)?}))
        }
        ("POST", "hosted/attach") => (200, crate::sessions::attach(&by, &s("runner").unwrap_or_else(|| caller.clone()),
            &s("agent_session").unwrap_or_default(), &s("title").unwrap_or_default(), &body["local"], s("branch").as_deref(),
            &s("owner").unwrap_or_default())?),
        ("POST", p) if p.starts_with("hosted/") && p.matches('/').count() == 2 => {
            let (id, verb) = p["hosted/".len()..].split_once('/').unwrap_or(("", ""));
            match verb {
                "files" => { crate::sessions::put_files(id, body)?; ok }
                "push" => {
                    let items = body["items"].as_array().cloned().unwrap_or_default();
                    let n = crate::sessions::push(id, &items, s("status").as_deref(), &s("runner").unwrap_or_else(|| caller.clone()),
                                                  s("agent_session").as_deref(), body.get("queue").filter(|q| !q.is_null()))?;
                    (200, json!({"next": n}))
                }
                "reopen" => {
                    if body["restart"] == true {
                        crate::sessions::take_back(id, &s("runner").unwrap_or_else(|| caller.clone()), &by)?;
                    } else {
                        crate::sessions::reopen(id, &by, &s("why").unwrap_or_default())?;
                    }
                    ok
                }
                "say" => { crate::sessions::tell(id, "message", body, &by)?; ok }
                // Put away, or back: the session's own list and its board card both.
                "archive" => {
                    let on = body["on"] != false;
                    crate::sessions::set_archived(id, on)?;
                    crate::collab::set_archived(&format!("session-{id}"), on, &by)?;
                    // A person's archive is "done": a session still open in an editor ends there
                    // too. Not a mirror's own (the editor archived or deleted it itself).
                    if on && who.principal.as_ref().is_some_and(|x| x.account.is_some()) {
                        crate::sessions::archived_by_person(id, &by)?;
                    }
                    ok
                }
                "done" => { crate::sessions::mark_done(id, &by)?; ok }
                "delete" => { crate::sessions::delete(id, &by)?; ok }
                "title" => (200, json!({"title": crate::sessions::set_title(id, &s("title").unwrap_or_default(), &by)?})),
                // When it carries on (sessions.rs, `wake`): set or moved, cancelled, or now.
                "wake" => {
                    if body["cancel"] == true {
                        crate::sessions::clear_wake(id, &by)?;
                        (200, json!({"wake": null}))
                    } else if body["now"] == true {
                        crate::sessions::wake(id, &by)?;
                        (200, json!({"wake": null}))
                    } else {
                        let at = match &body["at"] { Value::Number(n) => n.as_i64().map(|n| n.to_string()), v => v.as_str().map(str::to_string) };
                        let at = crate::sessions::when_of(at.as_deref(), s("in").as_deref(), registry::now())?;
                        // Moved on the page, a time keeps what it was to do.
                        let text = s("text").filter(|t| !t.trim().is_empty())
                            .or_else(|| crate::sessions::meta(id).ok().and_then(|m| m["wake"]["text"].as_str().map(str::to_string)))
                            .unwrap_or_default();
                        (200, json!({"wake": crate::sessions::set_wake(id, at, &text, &by)?}))
                    }
                }
                // What it waits on the person for (sessions.rs, `awaits`): set or done by its
                // agent; given, put off or declined on the page.
                "awaits" => {
                    let person = who.principal.as_ref().filter(|p| p.account.is_some());
                    if let Some(value) = s("value") {
                        // A secret goes where the session said: changing the hub's credentials is an admin's.
                        if !person.is_some_and(|p| crate::accounts::at_least(&p.role, "admin")) {
                            bail!("a secret is given by a person with the admin role, on the page");
                        }
                        crate::sessions::give_awaited(id, &value, &by)?;
                    } else if body["decline"] == true {
                        crate::sessions::decline_awaited(id, &by)?;
                    } else if body["snooze"].is_i64() {
                        crate::sessions::snooze_awaits(id, body["snooze"].as_i64().unwrap_or(0), &by)?;
                    } else if body["done"] == true {
                        crate::sessions::clear_awaits(id, "done", &by)?;
                    } else {
                        let secret = match s("secret") {
                            Some(spec) => crate::sessions::secret_of(&spec, s("url").as_deref())?,
                            None => Value::Null,
                        };
                        let a = crate::sessions::set_awaits(id, &s("text").unwrap_or_default(), &s("steps").unwrap_or_default(), &secret, &by)?;
                        return Ok((200, json!({"awaits": a})));
                    }
                    ok
                }
                "project" => (200, json!({"repo": crate::sessions::set_project(id, &s("repo").unwrap_or_default(), &by)?})),
                "import" => {
                    let items = body["items"].as_array().cloned().unwrap_or_default();
                    (200, json!({"next": crate::sessions::import_items(id, &items, body["done"] == true)?}))
                }
                "permit" | "answer" | "mode" | "model" | "autopilot" | "queue" | "cancel" | "stop" | "handoff" | "handback" => {
                    crate::sessions::tell(id, verb, body, &by)?;
                    ok
                }
                // The session's machines: it has changed hands (sessions.rs).
                "handed" => {
                    crate::sessions::handed(id, &s("sha").unwrap_or_default(), body["uncommitted"] == true)?;
                    ok
                }
                "handed_back" => {
                    crate::sessions::handed_back(id, &s("sha").unwrap_or_default())?;
                    ok
                }
                _ => (404, json!({"error": "no such endpoint"})),
            }
        }
        // A card put away (or back): any session's, on the board.
        ("POST", "archive") => {
            let session = s("session").unwrap_or_default();
            let on = body["on"] != false;
            crate::collab::set_archived(&session, on, &by)?;
            // A session midas runs is put away in its own list too.
            if let Some(id) = session.strip_prefix("session-").filter(|id| crate::sessions::meta(id).is_ok()) {
                crate::sessions::set_archived(id, on)?;
            }
            ok
        }
        ("POST", "decisions/add") => {
            let list = |k: &str| -> Vec<String> { body[k].as_array().into_iter().flatten()
                .filter_map(|v| v.as_str().map(str::to_string)).collect() };
            let (question, options, with) = (s("question").unwrap_or_default(), list("options"), list("with"));
            let id = crate::collab::decision_add(&owner, &question, &options, &with)?;
            (200, json!({"id": id}))
        }
        // Root for a while (admin.rs). A session asks with its key; only the person, logged in on
        // the page as an admin, answers — and root believes only their passkey's signature.
        ("POST", "admin/request") => {
            if p.account.is_some() {
                return Ok((403, json!({"error": "a session asks for root, with its key"})));
            }
            let minutes = body["minutes"].as_u64().unwrap_or(30) as u32;
            match crate::admin::request(&owner, &s("reason").unwrap_or_default(), minutes) {
                Ok(id) => (200, json!({"id": id})),
                Err(e) => (409, json!({"error": format!("{e:#}")})),
            }
        }
        ("POST", "admin/grant" | "admin/decline") => {
            if !(p.account.is_some() && crate::accounts::at_least(&p.role, "admin")) {
                return Ok((403, json!({"error": "root is granted by a person with the admin role, on the page"})));
            }
            let id = s("id").unwrap_or_default();
            let r = if path == "admin/decline" {
                crate::admin::decline(&id, &by)
            } else {
                serde_json::from_value::<crate::admin::Assertion>(body["assertion"].clone())
                    .map_err(|e| anyhow::anyhow!("the passkey's answer: {e}"))
                    .and_then(|a| crate::admin::grant(&id, body["issued_at"].as_i64().unwrap_or(0), a, &by))
            };
            match r {
                Ok(v) => (200, v),
                Err(e) => (409, json!({"error": format!("{e:#}")})),
            }
        }
        ("POST", "admin/close") => {
            // The session that has the window, or the person; closing takes nothing from anyone else.
            let st = crate::admin::read_status();
            if st["open"].is_null() {
                return Ok(ok);
            }
            let person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
            if !person && st["open"]["session"].as_str() != Some(owner.as_str()) {
                return Ok((403, json!({"error": "the window is another session's; the person can close it on the page"})));
            }
            crate::admin::close(&by, if person { "closed on the page" } else { "the session was done" })?;
            ok
        }
        ("POST", "decisions/answer") => {
            let d = crate::collab::decision_answer(&s("id").unwrap_or_default(), &s("choice").unwrap_or_default(),
                &format!("{caller}:{owner}"), s("note").as_deref())?;
            (200, d)
        }
        ("POST", "intent") => match registry::set_intent(&owner, s("text").as_deref(), body["minutes"].as_i64())? {
            Some(node) => (200, json!({"node": node})),
            None => (404, json!({"error": "you hold no node"})),
        },
        ("POST", "yield") => match registry::set_yield(&owner, body["on"] != false)? {
            Some((node, released)) => (200, json!({"node": node, "released": released})),
            None => (404, json!({"error": "you hold no node"})),
        },
        ("POST", "todos/add") => {
            let id = crate::collab::todo_add(&format!("{caller}:{owner}"), &s("for").unwrap_or_else(|| "any".into()),
                &s("text").unwrap_or_default())?;
            (200, json!({"id": id}))
        }
        // What the session starting in `owner` should do first: by the caller
        // it speaks as, which says which machine it is on.
        ("POST", "todos/take") => {
            let todos = crate::collab::todo_take(&caller, &owner)?;
            (200, json!({"context": crate::collab::todo_context(&todos), "todos": todos}))
        }
        ("POST", "todos/done") => {
            crate::collab::todo_done(&s("id").unwrap_or_default(), &format!("{caller}:{owner}"), s("note").as_deref())?;
            ok
        }
        ("POST", "reserve") => {
            let n = crate::collab::reserve(&s("namespace").unwrap_or_default(), &owner,
                body["from"].as_i64().unwrap_or(0), s("why").as_deref())?;
            (200, json!({"number": n}))
        }
        ("POST", "land/claim") => match registry::land_claim(&owner, branch().as_deref(), s("purpose").as_deref())? {
            Ok(turn) => (200, turn),
            Err(why) => (409, why),
        },
        ("POST", "land/renew") => match registry::land_renew(&owner, s("step").as_deref())? {
            true => ok,
            false => (404, json!({"error": "it is not your turn to land"})),
        },
        ("POST", "land/release") => match registry::land_release(&owner, s("outcome").as_deref(), s("sha").as_deref())? {
            true => {
                // A landing moved some project's main: the planner reads the
                // mirror, and a repository whose git server sends no push note
                // (about-cartopolis, podium) was otherwise fetched a quarter of
                // an hour later at best — s530's landing never reached its
                // deploy (2026-10-31).
                if s("outcome").as_deref() == Some("landed") {
                    crate::util::spawn_detached("a fetch after a landing", || {
                        for r in crate::conf::hub().shipped_repos() {
                            let Ok(repo) = crate::mirror::repo_name(&r) else { continue };
                            if let Err(e) = crate::mirror::fetch_now(&repo) {
                                events::emit("error", json!({"what": format!("refreshing {repo} after a landing: {e:#}")}));
                            }
                        }
                    });
                }
                ok
            }
            false => (404, json!({"error": "you are neither landing nor in line to"})),
        },
        ("POST", "drain") => {
            registry::drain(&s("node").unwrap_or_default(), s("why").as_deref(), &format!("{caller}:{owner}"))?;
            ok
        }
        ("POST", "nodes/add") => { registry::add_node(body)?; crate::hubsetup::refresh_ssh()?; ok }
        // A new project, hosted here (hosted.rs): its repository and its landing.
        ("POST", "projects/create") => {
            let default_owner = crate::conf::hub().first_repo().and_then(|r| r.split('/').next().map(str::to_string))
                .unwrap_or_else(|| "midas".into());
            let new_owner = s("repo_owner").unwrap_or(default_owner);
            let name = s("name").unwrap_or_default();
            match crate::hosted::create(&crate::hosted::New {
                owner: &new_owner, name: &name, description: &s("description").unwrap_or_default(),
                public: body["public"] == true, gate: s("gate").as_deref(), gate_nodes: s("gate_nodes").as_deref(), by: &by,
            }) {
                Ok(v) => (200, v),
                Err(e) => (409, json!({"error": format!("{e:#}")})),
            }
        }
        ("POST", "projects/set") => {
            let by_person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
            // On the page a project's settings are an admin's; a caller key (an agent's project_set) as before.
            if p.account.is_some() && !by_person {
                return Ok((403, json!({"error": "a project's settings are an admin's to change"})));
            }
            match crate::hosted::set(&s("repo").unwrap_or_default(), body, &by, by_person) {
                Ok(v) => (200, v),
                Err(e) => (409, json!({"error": format!("{e:#}")})),
            }
        }
        // Another name for a hosted project (hosted.rs `rename`): an admin's on the page, any caller key's.
        ("POST", "projects/rename") => {
            if p.account.is_some() && !crate::accounts::at_least(&p.role, "admin") {
                return Ok((403, json!({"error": "renaming a project is an admin's"})));
            }
            match crate::hosted::rename(&s("repo").unwrap_or_default(), &s("to").unwrap_or_default(), &by) {
                Ok(v) => (200, v),
                Err(e) => (409, json!({"error": format!("{e:#}")})),
            }
        }
        // Deleting one is the person's alone, an admin logged in on the page (hosted.rs `delete`).
        ("POST", "projects/delete") => {
            let by_person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
            if p.account.is_some() && !by_person {
                return Ok((403, json!({"error": "deleting a project is an admin's"})));
            }
            match crate::hosted::delete(&s("repo").unwrap_or_default(), &by, by_person) {
                Ok(v) => (200, v),
                Err(e) => (409, json!({"error": format!("{e:#}")})),
            }
        }
        ("POST", "nodes/remove") => { registry::remove_node(&s("id").unwrap_or_default())?; crate::hubsetup::refresh_ssh()?; ok }
        ("POST", "deploy") => {
            let target = s("target").unwrap_or_default();
            let by = format!("{caller}:{owner}");
            let req = crate::deploy::request(&target, s("sha").as_deref(), &by, s("unverified").as_deref())?;
            // A person deploying by hand is done holding: what follows landings goes out again.
            if p.account.is_some() {
                crate::ship::release(&by)?;
            }
            (200, req)
        }
        // Hold the deploys that follow landings (a landing the person wants on main but not live yet), and end a hold.
        // A browser asking to be woken when something needs its person (push.rs): a person's, by their login.
        ("POST", "push/subscribe") => match &p.account {
            Some(a) => { crate::push::subscribe(a, &s("endpoint").unwrap_or_default())?; ok }
            None => (403, json!({"error": "notifications are a person's: log in"})),
        },
        // Or an ntfy topic, for a phone Web Push cannot reach; an empty topic removes it.
        ("POST", "push/ntfy") => match &p.account {
            Some(a) => {
                let topic = s("topic").filter(|t| !t.trim().is_empty());
                let topic = crate::push::set_ntfy(a, topic.as_deref().map(str::trim), &s("page").unwrap_or_default())?;
                (200, json!({"ok": true, "topic": topic}))
            }
            None => (403, json!({"error": "notifications are a person's: log in"})),
        },
        ("POST", "push/ntfy/test") => match &p.account {
            Some(a) => { crate::push::ntfy_test(a)?; ok }
            None => (403, json!({"error": "notifications are a person's: log in"})),
        },
        ("POST", "push/unsubscribe") => (200, json!({"removed": crate::push::unsubscribe(&s("endpoint").unwrap_or_default())?})),
        ("POST", "deploy/hold") => (200, json!({"held": crate::ship::hold(&by, &s("why").unwrap_or_default())?})),
        ("POST", "deploy/release") => (200, json!({"released": crate::ship::release(&by)?})),
        // A session at work putting off an announced deploy that would restart what it uses (ship.rs).
        ("POST", "deploy/defer") => (200, json!({"deferred": crate::ship::defer(&s("target").unwrap_or_default(), body["minutes"].as_i64().unwrap_or(10), &s("why").unwrap_or_default(), &by)?})),
        ("POST", "bot/secrets") => {
            let by = format!("{caller}:{owner}");
            let value = if body["remove"] == true { None } else { Some(s("value").unwrap_or_default()) };
            (200, crate::botsecrets::set(&s("target").unwrap_or_default(), &s("name").unwrap_or_default(), value.as_deref(), &by)?)
        }
        ("GET", "bot/secrets") => (200, crate::botsecrets::names()),
        ("POST", "land/targets") => {
            let picked: Vec<String> = body["targets"].as_array().into_iter().flatten()
                .filter_map(|t| t.as_str().map(str::to_string)).collect();
            (200, crate::ship::choose(&s("repo").unwrap_or_default(), &s("sha").unwrap_or_default(), &picked,
                                      s("asked").as_deref(), &format!("{caller}:{owner}"))?)
        }
        ("POST", "verified") => {
            let sha = s("sha").unwrap_or_default();
            (200, crate::deploy::record_verified(&sha, &format!("{caller}:{owner}"), body)?)
        }
        ("POST", "nodes/rename") => {
            registry::rename_node(&s("id").unwrap_or_default(), &s("to").unwrap_or_default())?;
            crate::hubsetup::refresh_ssh()?;
            ok
        }
        _ => (404, json!({"error": "no such endpoint"})),
    })
}

/// The hub's own address (what it listens on), or loopback.
fn from_this_machine(peer: &str) -> bool {
    let listen = crate::conf::hub().listen;
    let own = listen.rsplit_once(':').map_or(listen.as_str(), |(h, _)| h).trim_matches(['[', ']']);
    peer == own || peer == "127.0.0.1" || peer == "::1"
}

/// The midas a node of `platform` should run: this very binary for a node of
/// the hub's own platform, else the copy `hub setup --node-binary` kept — but
/// only if it is marked as this build, so a copy left from an earlier setup is
/// never handed out, and no node is ever taken back to an older midas.
fn node_binary(platform: &str) -> Option<PathBuf> {
    node_binary_in(Path::new(crate::hubsetup::NODE_BIN_DIR), platform)
}

fn node_binary_in(dir: &Path, platform: &str) -> Option<PathBuf> {
    if !crate::node::is_platform(platform) {
        return None;
    }
    if platform == crate::node::platform() {
        return Some(PathBuf::from("/proc/self/exe")).filter(|p| p.exists());
    }
    let file = dir.join(format!("midas-{platform}"));
    let build = std::fs::read_to_string(dir.join(format!("midas-{platform}.build"))).ok()?;
    (build.trim() == crate::VERSION && file.is_file()).then_some(file)
}

/// A node's own messages are accepted only from its own WireGuard address:
/// WireGuard has already proved which machine sent them.
fn from_node(node: &str, peer: &str) -> Option<(u16, Value)> {
    let n = registry::nodes().into_iter().find(|n| n["id"] == node)?;
    (n["address"].as_str() != Some(peer)).then(|| {
        events::emit("refused", json!({"why": "a node message from another address", "node": node, "peer": peer}));
        (403, json!({"error": format!("{node} speaks from its own address, not {peer}")}))
    })
}

/// How long a node may go without a reading before it counts as down. Nodes
/// send one a minute; three missed is a machine asleep or a dead container.
const HEARTBEAT_LOST_S: i64 = 180;

/// A node is in the pool while it reports and out of it when it stops. Only
/// `enabled` is touched — a drain is a person's decision and stays.
fn watch_heartbeats() {
    let mut tick = 0u64;
    loop {
        std::thread::sleep(Duration::from_secs(30));
        // The pool's size, for the history the waits are measured against.
        if tick % 20 == 0 {
            crate::builds::sample_pool();
        }
        // Every time, whether an editor still has the sessions it mirrors open.
        crate::sessions::sweep_mirrors();
        // And every five minutes, whether a node somebody waits for sits unused.
        if tick % 10 == 5 {
            crate::collab::nudge_idle_holders();
        }
        // And every ten minutes, notes nobody read in two days go.
        if tick % 20 == 15 {
            crate::collab::expire_notes();
        }
        // Every time, root's answers on admin windows, told to the sessions that asked (admin.rs).
        crate::admin::tick();
        // Every time, what has landed and waits for a deploy (ship.rs), and the sessions to finish once theirs is live.
        crate::ship::tick();
        crate::sessions::finish_sweep();
        // And the templates' schedules: runs' outcomes, pauses, and what is due (templates.rs).
        crate::templates::tick();
        // And the research tree's direction: researches read back as they end, and the next one started (tree.rs).
        crate::tree::tick();
        // And which Mac nodes' VMs to stop while nobody uses them, or start again (sleep.rs).
        if let Err(e) = crate::sleep::tick() {
            eprintln!("midas hub: sleep: {e:#}");
        }
        tick += 1;
        for n in registry::nodes() {
            let id = n["id"].as_str().unwrap_or("").to_string();
            let age = registry::reading(&id).and_then(|r| r["at"].as_i64()).map(|at| registry::now() - at);
            let alive = age.is_some_and(|a| a <= HEARTBEAT_LOST_S);
            let why = match (alive, age) {
                (true, _) => "heartbeat resumed".to_string(),
                (false, _) if n["asleep"].is_object() => "asleep: its VM was shut down while nobody used it".into(),
                (false, Some(a)) => format!("no heartbeat for {a}s"),
                (false, None) => "never sent a heartbeat".into(),
            };
            let _ = registry::set_online(&id, alive, &why);
        }
    }
}

fn lease(node: &str) -> Result<Value> {
    let mut reg = Locked::open()?;
    reg.reap();
    reg.commit()?;
    let l = reg.leases().get(node).cloned();
    Ok(json!({
        "node": node, "known": reg.node(node).is_some(), "leased": l.is_some(),
        "owner": l.as_ref().map(|l| l["owner"].clone()), "purpose": l.as_ref().map(|l| l["purpose"].clone()),
        "mode": l.as_ref().map(|l| registry::mode_of(l).as_str()),
        "since": l.as_ref().map(|l| l["claimed_at"].clone()), "renewed_at": l.as_ref().map(|l| l["renewed_at"].clone()),
    }))
}

fn respond(stream: &mut TcpStream, status: u16, ctype: &str, body: &[u8]) -> Result<()> {
    respond_with(stream, status, ctype, body, None)
}

fn respond_with(stream: &mut TcpStream, status: u16, ctype: &str, body: &[u8], set_cookie: Option<&str>) -> Result<()> {
    let reason = match status {
        200 => "OK",
        204 => "No Content",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        409 => "Conflict",
        413 => "Payload Too Large",
        404 => "Not Found",
        422 => "Unprocessable Entity",
        _ => "Error",
    };
    write!(
        stream,
        // No caching: the page and the state both change under a reload.
        "HTTP/1.1 {status} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-cache\r\n{}Connection: close\r\n\r\n",
        body.len(),
        set_cookie.map(|c| format!("Set-Cookie: {c}\r\n")).unwrap_or_default()
    )?;
    stream.write_all(body)?;
    Ok(())
}

fn lfs(
    stream: &mut TcpStream,
    reader: &mut BufReader<TcpStream>,
    method: &str,
    rest: &str,
    len: usize,
    bearer: &str,
    peer: &str,
    host: &str,
) -> Result<()> {
    const LFS_JSON: &str = "application/vnd.git-lfs+json";
    let Some(repo) = crate::mirror::check_token(bearer) else {
        events::emit("lfs_refused", json!({"peer": peer, "why": "no valid token"}));
        return respond(stream, 401, LFS_JSON, br#"{"message":"a token from midas hub git is required"}"#);
    };
    if let Some(oid) = rest.strip_prefix("objects/") {
        // An upload to a repository the hub hosts, with a token for one.
        if method == "PUT" {
            let upload = crate::mirror::check_token_op(bearer).is_some_and(|(_, op)| op == "upload");
            if !upload || !crate::hosted::is_hosted(&repo) {
                return respond(stream, 403, LFS_JSON, br#"{"message":"uploads go only to a repository the hub hosts"}"#);
            }
            return match crate::mirror::store_object(oid, reader, len as u64) {
                Ok(()) => {
                    events::emit("lfs_stored", json!({"repo": repo, "oid": oid, "size": len}));
                    respond(stream, 200, LFS_JSON, b"{}")
                }
                Err(e) => respond(stream, 422, LFS_JSON, json!({"message": format!("{e:#}")}).to_string().as_bytes()),
            };
        }
        if method != "GET" {
            return respond(stream, 422, LFS_JSON, br#"{"message":"download only"}"#);
        }
        let Some(path) = crate::mirror::cached_object(oid) else {
            return respond(stream, 404, LFS_JSON, br#"{"message":"not cached"}"#);
        };
        let mut f = std::fs::File::open(&path)?;
        let size = f.metadata()?.len();
        write!(
            stream,
            "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n"
        )?;
        std::io::copy(&mut f, stream)?;
        return Ok(());
    }
    // <owner>/<repo>.git/info/lfs/objects/batch, for the repo the token is for.
    let Some(r) = rest.strip_suffix("/info/lfs/objects/batch") else {
        return respond(stream, 404, LFS_JSON, br#"{"message":"no such LFS endpoint"}"#);
    };
    if crate::mirror::repo_name(r).ok().as_deref() != Some(repo.as_str()) || method != "POST" || len > 4 << 20 {
        return respond(stream, 422, LFS_JSON, br#"{"message":"wrong repository for this token"}"#);
    }
    let mut buf = vec![0u8; len];
    reader.read_exact(&mut buf)?;
    let body: Value = serde_json::from_slice(&buf).unwrap_or(Value::Null);
    match crate::mirror::batch(&repo, &body, bearer, host) {
        Ok(v) => respond(stream, 200, LFS_JSON, v.to_string().as_bytes()),
        Err(e) => {
            events::emit("error", json!({"what": format!("lfs batch for {repo}: {e:#}")}));
            respond(stream, 422, LFS_JSON, json!({"message": format!("{e:#}")}).to_string().as_bytes())
        }
    }
}

struct PublicGit<'a> {
    method: &'a str,
    rest: &'a str,
    len: usize,
    content_type: &'a str,
    git_protocol: &'a str,
    content_encoding: &'a str,
    host: &'a str,
    peer: &'a str,
    /// Reached over HTTPS at the proxy: the scheme of the LFS links it is given.
    https: bool,
}

/// `owner/name…` of a request for a repository the hub hosts, public or not, at
/// the site's root (`/<owner>/<name>`, `.git` or not): what goes to
/// `public_git`, which answers a private one as not there. Only a hosted
/// repository's two segments match, so the page's own places (`/sessions/s3`)
/// never do.
fn hosted_path(target: &str) -> Option<&str> {
    let rest = target.strip_prefix('/')?;
    let mut seg = rest.split(['/', '?']);
    let (owner, name) = (seg.next()?, seg.next()?);
    let name = name.trim_end_matches(".git");
    if owner.is_empty() || name.is_empty() || owner.starts_with('.') || name.starts_with('.') {
        return None;
    }
    crate::hosted::is_hosted(&format!("{owner}/{name}")).then_some(rest)
}

/// LFS for a public repository, without a login (`<name>.git/info/lfs/…`):
/// the batch, downloads only, points each object the store has at the
/// object's own path, which serves it. The store is shared by every hosted
/// repository, and an object is asked for by its sha256 — which only someone
/// who has its repository's pointer files knows.
fn public_lfs(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &PublicGit, repo: &str, tail: &str) -> Result<()> {
    const LFS_JSON: &str = "application/vnd.git-lfs+json";
    if let Some(oid) = tail.strip_prefix("objects/").filter(|o| *o != "batch" && !o.contains('/')) {
        let Some(path) = crate::mirror::cached_object(oid).filter(|_| g.method == "GET") else {
            return respond(stream, 404, LFS_JSON, br#"{"message":"no such object"}"#);
        };
        let mut f = std::fs::File::open(&path)?;
        let size = f.metadata()?.len();
        write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {size}\r\nConnection: close\r\n\r\n")?;
        std::io::copy(&mut f, stream)?;
        return Ok(());
    }
    if tail != "objects/batch" || g.method != "POST" || g.len > 4 << 20 {
        return respond(stream, 404, LFS_JSON, br#"{"message":"no such LFS endpoint"}"#);
    }
    let mut buf = vec![0u8; g.len];
    reader.read_exact(&mut buf)?;
    let body: Value = serde_json::from_slice(&buf).unwrap_or(Value::Null);
    if body["operation"] != "download" {
        return respond(stream, 403, LFS_JSON, br#"{"message":"read-only: downloads"}"#);
    }
    let base = format!("{}://{}/{}.git/info/lfs/objects", if g.https { "https" } else { "http" }, g.host, repo.trim_end_matches(".git"));
    let objects: Vec<Value> = body["objects"].as_array().into_iter().flatten().filter_map(|o| {
        let oid = o["oid"].as_str()?;
        let size = o["size"].as_u64().unwrap_or(0);
        Some(match crate::mirror::cached_object(oid) {
            Some(_) => json!({"oid": oid, "size": size, "actions": {"download": {"href": format!("{base}/{oid}")}}}),
            None => json!({"oid": oid, "size": size, "error": {"code": 404, "message": "not stored here"}}),
        })
    }).collect();
    events::emit("lfs_public", json!({"repo": repo, "objects": objects.len(), "peer": g.peer}));
    respond(stream, 200, LFS_JSON, json!({"transfer": "basic", "objects": objects}).to_string().as_bytes())
}

/// `/git/<owner>/<name>…` for a public hosted repository, with no login:
/// `.git/info/refs` and `.git/git-upload-pack` (a clone, through `git
/// http-backend`; never a push), `/archive/<rev>.tar.gz`, and the pages
/// (`codeview.rs`). Anything else, a private repository included, is a 404.
fn public_git(stream: &mut TcpStream, reader: &mut BufReader<TcpStream>, g: &PublicGit) -> Result<()> {
    let (path, query) = g.rest.split_once('?').unwrap_or((g.rest, ""));
    let mut seg = path.splitn(3, '/');
    let (owner, name, tail) = (seg.next().unwrap_or(""), seg.next().unwrap_or(""), seg.next().unwrap_or(""));
    let git_suffix = name.ends_with(".git");
    let name = name.trim_end_matches(".git");
    let not_found = |s: &mut TcpStream| respond(s, 404, "text/plain", b"no such public repository\n");
    let Ok(repo) = crate::mirror::repo_name(&format!("{owner}/{name}")) else { return not_found(stream) };
    if !crate::hosted::is_public(&repo) {
        return not_found(stream);
    }
    if git_suffix {
        if let Some(t) = tail.strip_prefix("info/lfs/") {
            return public_lfs(stream, reader, g, &repo, t);
        }
    }
    // Smart HTTP, for clones (Cargo's `git =`, anybody's `git clone`).
    if git_suffix {
        let fetch = matches!((g.method, tail), ("GET", "info/refs") | ("POST", "git-upload-pack"))
            && (tail != "info/refs" || query.split('&').any(|p| p == "service=git-upload-pack"));
        if !fetch || g.len > 16 << 20 {
            return respond(stream, 403, "text/plain", b"read-only: clones and fetches\n");
        }
        let mut body = vec![0u8; g.len];
        reader.read_exact(&mut body)?;
        let mut child = std::process::Command::new("git").arg("http-backend")
            .env_clear().env("PATH", std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".into()))
            .env("GIT_PROJECT_ROOT", crate::hosted::root()).env("GIT_HTTP_EXPORT_ALL", "1")
            .env("PATH_INFO", format!("/{}/{tail}", repo)).env("QUERY_STRING", query)
            .env("REQUEST_METHOD", g.method).env("CONTENT_TYPE", g.content_type).env("CONTENT_LENGTH", g.len.to_string())
            .env("GIT_PROTOCOL", g.git_protocol).env("HTTP_CONTENT_ENCODING", g.content_encoding).env("REMOTE_ADDR", g.peer)
            .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null())
            .spawn()?;
        let mut stdin = child.stdin.take().unwrap();
        let feeder = std::thread::spawn(move || {
            let _ = stdin.write_all(&body);
        });
        let mut out = BufReader::new(child.stdout.take().unwrap());
        // The CGI's headers, then its body as it comes.
        let mut status = "200 OK".to_string();
        let mut headers = String::new();
        loop {
            let mut h = String::new();
            if out.read_line(&mut h)? == 0 || h.trim().is_empty() {
                break;
            }
            match h.split_once(':') {
                Some((k, v)) if k.eq_ignore_ascii_case("status") => status = v.trim().to_string(),
                _ => headers.push_str(&format!("{}\r\n", h.trim_end())),
            }
        }
        write!(stream, "HTTP/1.1 {status}\r\n{headers}Connection: close\r\n\r\n")?;
        std::io::copy(&mut out, stream)?;
        let _ = feeder.join();
        let _ = child.wait();
        events::emit("git_public", json!({"repo": repo, "what": tail, "peer": g.peer}));
        return Ok(());
    }
    if g.method != "GET" {
        return respond(stream, 405, "text/plain", b"read-only\n");
    }
    // archive/<rev>.tar.gz: what Bun takes as a dependency.
    if let Some(rev) = tail.strip_prefix("archive/").and_then(|r| r.strip_suffix(".tar.gz")) {
        return archive(stream, &repo, rev);
    }
    use crate::codeview::Page;
    match crate::codeview::page(&repo, g.host, tail, query) {
        Ok(Some(Page::Html(html))) => respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()),
        // Text as text, never as HTML: a repository's page must not run on the hub's origin.
        Ok(Some(Page::Raw(bytes))) => {
            let ctype = if std::str::from_utf8(&bytes).is_ok() { "text/plain; charset=utf-8" } else { "application/octet-stream" };
            write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nX-Content-Type-Options: nosniff\r\nContent-Security-Policy: sandbox\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len())?;
            stream.write_all(&bytes)?;
            Ok(())
        }
        Ok(Some(Page::Moved(to))) => {
            write!(stream, "HTTP/1.1 301 Moved Permanently\r\nLocation: {to}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")?;
            Ok(())
        }
        Ok(None) | Err(_) => not_found(stream),
    }
}

/// A hosted repository at `rev` as a .tar.gz, its files under `<name>/`.
fn archive(stream: &mut TcpStream, repo: &str, rev: &str) -> Result<()> {
    let name = repo.trim_end_matches(".git").rsplit('/').next().unwrap_or("repo").to_string();
    if rev.is_empty() || rev.starts_with('-') || !rev.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {
        return respond(stream, 404, "text/plain", b"no such revision\n");
    }
    let out = std::process::Command::new("git").arg("-C").arg(crate::hosted::path(repo))
        .args(["archive", "--format=tar.gz", &format!("--prefix={name}/"), rev]).output()?;
    if !out.status.success() {
        return respond(stream, 404, "text/plain", b"no such revision\n");
    }
    write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/gzip\r\nContent-Disposition: attachment; filename=\"{name}.tar.gz\"\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", out.stdout.len())?;
    stream.write_all(&out.stdout)?;
    Ok(())
}

/// `GET /v1/repos/<owner>/<name>/<what>`: a hosted repository read through
/// the API, for sessions and the page. `q` is the query reader of `api`.
fn repo_read(rest: &str, q: &dyn Fn(&str) -> Option<String>) -> Result<(u16, Value)> {
    let mut parts = rest.splitn(3, '/');
    let (Some(owner), Some(name), Some(what)) = (parts.next(), parts.next(), parts.next()) else {
        return Ok((404, json!({"error": "repos/<owner>/<name>/show|log|branches|commit"})));
    };
    let repo = crate::mirror::repo_name(&format!("{owner}/{name}"))?;
    if !crate::hosted::is_hosted(&repo) {
        return Ok((404, json!({"error": format!("{} is not hosted here (a Forgejo project: the forgejo_* tools read it)", repo.trim_end_matches(".git"))})));
    }
    let rev = q("rev").map(|r| pct_decode(&r));
    let v = match what {
        "show" => crate::hosted::show(&repo, rev.as_deref(), &pct_decode(&q("path").unwrap_or_default()))?,
        "log" => json!(crate::hosted::log(&repo, rev.as_deref(), q("n").and_then(|n| n.parse().ok()).unwrap_or(30))?),
        "branches" => json!(crate::hosted::branches(&repo)?),
        "commit" => crate::hosted::commit(&repo, &rev.unwrap_or_else(|| "HEAD".into()))?,
        // What the project page says of it: how to get it, and its landing settings.
        "about" => {
            let r = crate::hosted::get(&repo).unwrap_or_default();
            let key = repo.trim_end_matches(".git");
            let ssh = crate::conf::hub().forgejo_ssh.trim_end_matches('/').to_string();
            json!({"repo": key, "description": r["description"], "public": r["visibility"] == "public",
                   "ssh": if ssh.is_empty() { crate::hosted::url(&repo) } else { format!("{ssh}/{key}.git") },
                   "head": crate::hosted::log(&repo, None, 1)?.first(), "project": r["project"]})
        }
        _ => return Ok((404, json!({"error": "show, log, branches, commit or about"}))),
    };
    Ok((200, v))
}

/// The callers allowed to use the hub's Forgejo proxy: `/srv/midas/callers.json`,
/// `{"<name>": {"key": "<random>", "token": "<Forgejo token>", "api"?: "…"}}`,
/// readable by the hub's user only. A caller is a trust level (the agent
/// container), and its token's permissions in Forgejo are its access (§8).
const CALLERS: &str = "/srv/midas/callers.json";

/// `MIDAS_CALLERS` names another file, for a hub that is not the workspace's: the
/// throwaway one `tests/e2e` runs unprivileged, beside its own `MIDAS_STATE`.
pub fn callers_file() -> String {
    std::env::var("MIDAS_CALLERS").unwrap_or_else(|_| CALLERS.into())
}

/// Who is asking, and as what.
struct Principal {
    /// A caller key's name, or `web` for a person.
    caller: String,
    /// The person's account, when it is one.
    account: Option<String>,
    role: String,
}

struct Who {
    /// Through the web proxy, which adds X-Forwarded-*: only ever a person,
    /// so a session counts and a key does not (a proxy that adds one would
    /// otherwise make everybody past it a caller).
    web: bool,
    principal: Option<Principal>,
    /// The session token from the cookie, for logging out.
    token: Option<String>,
    /// No Origin (not a browser), or this page's own.
    origin_ok: bool,
    /// Reached over HTTPS (at the proxy): the cookie can be Secure.
    https: bool,
    /// The address a person is at: the proxy's X-Forwarded-For.
    peer: String,
}

impl Who {
    fn new(key: &str, cookie: &str, origin: &str, fwd_for: &str, fwd_proto: &str, host: &str, peer: &str) -> Who {
        let web = !fwd_for.is_empty() || !fwd_proto.is_empty();
        let token = cookie.split(';').find_map(|c| c.trim().strip_prefix("midas_session=")).map(str::to_string)
            .filter(|t| !t.is_empty());
        let by_key = (!web).then(|| caller_for(key)).flatten().map(|(name, c)| Principal {
            caller: name,
            account: None,
            // Keys from before roles can do what they always could.
            role: c["role"].as_str().filter(|r| crate::accounts::rank(r).is_some()).unwrap_or("admin").to_string(),
        });
        let by_session = || token.as_deref().and_then(crate::accounts::session)
            .map(|(account, role)| Principal { caller: "web".into(), account: Some(account), role });
        let origin_host = origin.split("://").nth(1).unwrap_or("").trim_end_matches('/');
        Who {
            web,
            principal: by_key.or_else(by_session),
            token,
            origin_ok: origin.is_empty() || origin_host.eq_ignore_ascii_case(host),
            https: fwd_proto == "https",
            peer: fwd_for.split(',').next().map(str::trim).filter(|p| !p.is_empty()).unwrap_or(peer).to_string(),
        }
    }

    fn cookie(&self, token: &str, max_age: i64) -> String {
        format!("midas_session={token}; Path=/; HttpOnly; SameSite=Strict; Max-Age={max_age}{}",
                if self.https { "; Secure" } else { "" })
    }
}

/// `/v1/device/…`: a paired device's own paths. Pairing is open (the code is the
/// credential); the rest takes the device's token, which is good for nothing else.
/// `None` for every other path.
fn device_api(method: &str, path: &str, body: &Value, token: &str, who: &Who) -> Option<Result<(u16, Value)>> {
    let path = path.strip_prefix("/v1/device/")?;
    let s = |k: &str| body[k].as_str().unwrap_or("").to_string();
    if (method, path) == ("POST", "pair") {
        // An app, not a page: a browser's request from elsewhere is not one.
        if !who.origin_ok {
            return Some(Ok((403, json!({"error": "not from this page"}))));
        }
        return Some(crate::device::pair(&s("code"), &s("name"), &s("app"), &s("version")).map(|v| (200, v)));
    }
    let Some((id, dev)) = crate::device::by_token(token) else {
        events::emit("refused", json!({"why": "no device token", "path": format!("device/{path}"), "peer": who.peer}));
        return Some(Ok((401, json!({"error": "not a paired device: pair it again"}))));
    };
    Some(match (method, path) {
        ("GET", "me") => Ok((200, json!({"id": id, "name": dev["name"], "account": dev["account"]}))),
        ("GET", "sessions") => Ok((200, json!({"sessions": crate::device::sessions_for(&dev)}))),
        ("POST", "push") => crate::device::push(&id, &dev, body).map(|_| (200, json!({"ok": true}))),
        _ => Ok((404, json!({"error": "no such endpoint"}))),
    })
}

/// `/v1/login`, `/v1/logout` and `/v1/setup…`: open to anyone (that is the
/// point), and answered with a cookie to set. `None` for every other path.
fn login_api(method: &str, path: &str, body: &Value, who: &Who) -> Option<Result<(u16, Value, Option<String>)>> {
    let s = |k: &str| body[k].as_str().unwrap_or("").to_string();
    let path = path.strip_prefix("/v1/")?;
    let from_elsewhere = || Ok((403, json!({"error": "not from this page"}), None));
    Some(match (method, path) {
        ("POST", "login") if !who.origin_ok => from_elsewhere(),
        ("POST", "login") => match crate::accounts::login(&s("name"), &s("password"), &s("code"), &who.peer) {
            Ok((token, role)) => Ok((200, json!({"account": s("name"), "role": role}), Some(who.cookie(&token, 7 * 86400)))),
            Err(e) => Ok((401, json!({"error": format!("{e:#}")}), None)),
        },
        ("POST", "logout") => {
            if let Some(t) = &who.token {
                crate::accounts::logout(t);
            }
            Ok((200, json!({"ok": true}), Some(who.cookie("", 0))))
        }
        ("GET", p) if p.starts_with("setup/") => crate::accounts::setup_info(&p["setup/".len()..], "midas").map(|v| (200, v, None)),
        ("POST", "setup") if !who.origin_ok => from_elsewhere(),
        ("POST", "setup") => crate::accounts::setup_complete(&s("token"), &s("password"), &s("code"))
            .map(|codes| (200, json!({"recovery": codes}), None)),
        _ => return None,
    })
}

fn caller_for(key: &str) -> Option<(String, Value)> {
    if key.len() < 32 {
        return None;
    }
    let all: Value = serde_json::from_str(&std::fs::read_to_string(callers_file()).ok()?).ok()?;
    all.as_object()?.iter().find_map(|(name, c)| {
        let k = c["key"].as_str()?;
        // Compare every byte, so the time taken does not say how much matched.
        let same = k.len() == key.len() && k.bytes().zip(key.bytes()).fold(0u8, |d, (a, b)| d | (a ^ b)) == 0;
        // A key that only started sessions (`--starts`, retired 2026-11-06)
        // would read as a plain steer key without its narrowing: it is no key.
        (same && c.get("starts").is_none()).then(|| (name.clone(), c.clone()))
    })
}

/// `/v1/forgejo/<api path>`: one Forgejo API call made with the token the hub
/// holds for the calling key, so a session needs no Forgejo token of its own.
fn forgejo_proxy(
    stream: &mut TcpStream,
    reader: &mut BufReader<TcpStream>,
    method: &str,
    path: &str,
    len: usize,
    bearer: &str,
    peer: &str,
) -> Result<()> {
    let Some((name, caller)) = caller_for(bearer) else {
        events::emit("forgejo_refused", json!({"peer": peer, "path": path}));
        return respond(stream, 401, "application/json", br#"{"message":"no such caller key"}"#);
    };
    if !matches!(method, "GET" | "POST" | "PATCH" | "PUT" | "DELETE") || !path.starts_with('/') || len > 4 << 20 {
        return respond(stream, 422, "application/json", br#"{"message":"bad request"}"#);
    }
    let mut buf = vec![0u8; len];
    reader.read_exact(&mut buf)?;
    let body = (len > 0).then(|| String::from_utf8_lossy(&buf).to_string());
    // A repository the hub hosts is not Forgejo's to answer for, even while
    // Forgejo keeps its old copy (hosted::import): its branches are read here, in
    // Forgejo's shape, and anything else is pointed at what replaces it.
    if let Some((code, v)) = forgejo_for_hosted(method, path) {
        events::emit("forgejo_call", json!({"actor": name, "method": method, "path": path.split('?').next().unwrap_or(""),
                                            "status": code, "peer": peer, "hosted": true}));
        return respond(stream, code, "application/json", v.to_string().as_bytes());
    }
    let conf_api = crate::conf::hub().forgejo_api;
    if conf_api.is_empty() && caller["api"].as_str().is_none() {
        return respond(stream, 404, "application/json",
            br#"{"message":"this workspace has no Forgejo: its repositories are the hub's (project_read, project_create)"}"#);
    }
    let api = caller["api"].as_str().unwrap_or(&conf_api);
    let token = caller["token"].as_str().unwrap_or("");
    let (code, text) = match crate::mcp::curl_forgejo(api, token, method, path, body.as_deref()) {
        Ok(r) => r,
        Err(e) => (502, json!({"message": format!("{e:#}")}).to_string()),
    };
    events::emit("forgejo_call", json!({
        "actor": name, "method": method, "path": path.split('?').next().unwrap_or(""), "status": code, "peer": peer,
    }));
    respond(stream, code, "application/json", text.as_bytes())
}

/// The answer to a Forgejo API call about a repository the hub hosts, or none
/// when the call is not about one.
pub(crate) fn forgejo_for_hosted(method: &str, path: &str) -> Option<(u16, Value)> {
    let rest = path.strip_prefix("/repos/")?;
    let mut seg = rest.split(['/', '?']);
    let (owner, name, what) = (seg.next()?, seg.next()?, seg.next().unwrap_or(""));
    let repo = format!("{owner}/{name}");
    if !crate::hosted::is_hosted(&repo) {
        return None;
    }
    if method == "GET" && what == "branches" {
        let list: Vec<Value> = crate::hosted::branches(&repo).ok()?.into_iter()
            .map(|b| json!({"name": b["name"], "commit": {"id": b["sha"], "timestamp": b["at"]}})).collect();
        return Some((200, json!(list)));
    }
    Some((410, json!({"message": format!(
        "{repo} is hosted by midas, not Forgejo: read it with project_read (or `midas project show|log|branches`), \
         change its landing with project_set; there are no pull requests or issues")})))
}

/// A minimal HTTP client for the node side: the node asks one question of one
/// server, and pulling in a TLS-capable client for it would be all cost.
pub fn request(base: &str, method: &str, path: &str, body: Option<&str>) -> Result<(u16, String)> {
    request_auth(base, method, path, body, None)
}

/// A GET of bytes into `dest` (a node taking the hub's midas). Anything but a
/// 200 with the whole body promised is an error, and leaves nothing behind.
pub fn download(base: &str, path: &str, dest: &Path) -> Result<()> {
    let addr = base.trim_start_matches("http://").trim_end_matches('/');
    let mut s = TcpStream::connect_timeout(&addr.parse().with_context(|| format!("hub address {addr}"))?, Duration::from_secs(4))?;
    s.set_read_timeout(Some(Duration::from_secs(60)))?;
    write!(s, "GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n")?;
    let mut all = Vec::new();
    s.read_to_end(&mut all)?;
    let split = all.windows(4).position(|w| w == b"\r\n\r\n").context("no HTTP header in the answer")?;
    let head = String::from_utf8_lossy(&all[..split]);
    let body = &all[split + 4..];
    let status: u16 = head.split_whitespace().nth(1).and_then(|c| c.parse().ok()).unwrap_or(0);
    if status != 200 {
        bail!("the hub answered {status} for {path}: {}", String::from_utf8_lossy(&body[..body.len().min(200)]));
    }
    let promised = head.lines().find_map(|l| {
        let (k, v) = l.split_once(':')?;
        k.trim().eq_ignore_ascii_case("content-length").then(|| v.trim().parse::<usize>().ok()).flatten()
    });
    if promised != Some(body.len()) {
        bail!("{path}: {} bytes of {promised:?}", body.len());
    }
    std::fs::write(dest, body).with_context(|| format!("writing {}", dest.display()))
}

/// Requests to the hub this process has under way (`in_flight`).
static IN_FLIGHT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Whether this process is waiting for the hub right now: what a hook's time
/// limit asks before it takes the hub for down (hook.rs), rather than for a
/// slow `git diff` of its own.
pub fn in_flight() -> bool {
    IN_FLIGHT.load(std::sync::atomic::Ordering::SeqCst) > 0
}

pub fn request_auth(base: &str, method: &str, path: &str, body: Option<&str>, bearer: Option<&str>) -> Result<(u16, String)> {
    // A node asks short questions; a Forgejo call through the proxy can take a minute.
    request_auth_for(base, method, path, body, bearer, Duration::from_secs(if bearer.is_some() { 75 } else { 6 }))
}

/// `request_auth`, waiting up to `wait` for the answer (a device call: as long as the tool takes).
pub fn request_auth_for(base: &str, method: &str, path: &str, body: Option<&str>, bearer: Option<&str>, wait: Duration) -> Result<(u16, String)> {
    use std::sync::atomic::Ordering;
    struct Flight;
    impl Drop for Flight {
        fn drop(&mut self) {
            IN_FLIGHT.fetch_sub(1, Ordering::SeqCst);
        }
    }
    IN_FLIGHT.fetch_add(1, Ordering::SeqCst);
    let _flight = Flight;
    let addr = base.trim_start_matches("http://").trim_end_matches('/');
    let mut s = TcpStream::connect_timeout(
        &addr.parse().with_context(|| format!("hub address {addr}"))?,
        Duration::from_secs(4),
    )?;
    s.set_read_timeout(Some(wait))?;
    let body = body.unwrap_or("");
    let auth = bearer.map(|k| format!("Authorization: Bearer {k}\r\n")).unwrap_or_default();
    write!(
        s,
        "{method} {path} HTTP/1.1\r\nHost: {addr}\r\n{auth}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    )?;
    let mut resp = String::new();
    s.read_to_string(&mut resp)?;
    let status = resp.split_whitespace().nth(1).and_then(|c| c.parse().ok()).unwrap_or(0);
    let payload = resp.split_once("\r\n\r\n").map(|(_, b)| b.to_string()).unwrap_or_default();
    Ok((status, payload))
}

/// A POST of bytes as they are (a session's media), with headers of its own.
pub fn request_bytes(base: &str, path: &str, body: &[u8], headers: &[(&str, String)], bearer: &str) -> Result<(u16, String)> {
    let addr = base.trim_start_matches("http://").trim_end_matches('/');
    let mut s = TcpStream::connect_timeout(&addr.parse().with_context(|| format!("hub address {addr}"))?, Duration::from_secs(4))?;
    s.set_read_timeout(Some(Duration::from_secs(120)))?;
    let extra: String = headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect();
    write!(s, "POST {path} HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {bearer}\r\n{extra}\
               Content-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len())?;
    s.write_all(body)?;
    let mut resp = String::new();
    s.read_to_string(&mut resp)?;
    let status = resp.split_whitespace().nth(1).and_then(|c| c.parse().ok()).unwrap_or(0);
    let payload = resp.split_once("\r\n\r\n").map(|(_, b)| b.to_string()).unwrap_or_default();
    Ok((status, payload))
}

/// A GET of bytes as they are (a session's transcript), with a caller key.
pub fn get_bytes(base: &str, path: &str, bearer: &str) -> Result<(u16, Vec<u8>)> {
    let addr = base.trim_start_matches("http://").trim_end_matches('/');
    let mut s = TcpStream::connect_timeout(&addr.parse().with_context(|| format!("hub address {addr}"))?, Duration::from_secs(4))?;
    s.set_read_timeout(Some(Duration::from_secs(120)))?;
    write!(s, "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {bearer}\r\nConnection: close\r\n\r\n")?;
    let mut resp = Vec::new();
    s.read_to_end(&mut resp)?;
    let at = resp.windows(4).position(|w| w == b"\r\n\r\n").context("no answer from the hub")?;
    let head = String::from_utf8_lossy(&resp[..at]);
    let status = head.split_whitespace().nth(1).and_then(|c| c.parse().ok()).unwrap_or(0);
    Ok((status, resp[at + 4..].to_vec()))
}

/// Text in a header: anything but plain ASCII as `%XX`.
pub fn pct_encode(s: &str) -> String {
    s.bytes().map(|b| if b.is_ascii_alphanumeric() || b" .,-_()!?'".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
}

pub(crate) fn pct_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        let hex = (b[i] == b'%').then(|| s.get(i + 1..i + 3)).flatten().and_then(|h| u8::from_str_radix(h, 16).ok());
        match hex {
            Some(x) => {
                out.push(x);
                i += 3;
            }
            None => {
                out.push(b[i]);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).to_string()
}

/// `Range: bytes=a-b` (or `a-`, or `-n` for the last n) as first and last byte, when it fits.
fn byte_range(range: &str, size: u64) -> Option<(u64, u64)> {
    let (a, b) = range.strip_prefix("bytes=")?.split_once('-')?;
    let last = size.checked_sub(1)?;
    let (a, b) = match (a.trim().parse::<u64>().ok(), b.trim().parse::<u64>().ok()) {
        (Some(a), Some(b)) => (a, b.min(last)),
        (Some(a), None) => (a, last),
        (None, Some(n)) if n > 0 => (size.saturating_sub(n), last),
        _ => return None,
    };
    (a <= b).then_some((a, b))
}

/// A shown file's bytes, a range of them where the browser asks (a film is
/// seeked that way, and Safari plays none without it). Sandboxed: an SVG is a
/// picture here, never a page.
fn media_get(stream: &mut TcpStream, path: &std::path::Path, range: &str) -> Result<()> {
    let mut f = std::fs::File::open(path)?;
    let size = f.metadata()?.len();
    let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
    let common = format!("Content-Type: {}\r\nAccept-Ranges: bytes\r\nContent-Security-Policy: sandbox\r\n\
                          X-Content-Type-Options: nosniff\r\nCache-Control: private, max-age=3600\r\nConnection: close\r\n",
                         crate::sessions::mime_of(&name));
    match byte_range(range, size) {
        Some((a, b)) => {
            write!(stream, "HTTP/1.1 206 Partial Content\r\n{common}Content-Range: bytes {a}-{b}/{size}\r\nContent-Length: {}\r\n\r\n", b - a + 1)?;
            std::io::Seek::seek(&mut f, std::io::SeekFrom::Start(a))?;
            std::io::copy(&mut std::io::Read::take(f, b - a + 1), stream)?;
        }
        None => {
            write!(stream, "HTTP/1.1 200 OK\r\n{common}Content-Length: {size}\r\n\r\n")?;
            std::io::copy(&mut f, stream)?;
        }
    }
    Ok(())
}

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

    // Its own binary is /proc/self/exe: Linux only, so a landing gated on a Mac node passes without it.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_node_is_offered_only_this_build_never_a_copy_left_from_an_earlier_one() {
        let dir = std::env::temp_dir().join(format!("midas-node-bin-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let own = crate::node::platform();
        assert_eq!(node_binary_in(&dir, &own), Some(PathBuf::from("/proc/self/exe")), "its own platform: this very binary");
        assert_eq!(node_binary_in(&dir, "macos-aarch64"), None, "nothing kept for it");
        std::fs::write(dir.join("midas-macos-aarch64"), b"bin").unwrap();
        std::fs::write(dir.join("midas-macos-aarch64.build"), "0ldbuild\n").unwrap();
        assert_eq!(node_binary_in(&dir, "macos-aarch64"), None, "kept by an earlier setup");
        std::fs::write(dir.join("midas-macos-aarch64.build"), format!("{}\n", crate::VERSION)).unwrap();
        assert_eq!(node_binary_in(&dir, "macos-aarch64"), Some(dir.join("midas-macos-aarch64")));
        assert_eq!(node_binary_in(&dir, "../etc"), None, "a platform is no path");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_film_is_served_in_the_ranges_the_browser_asks_for() {
        assert_eq!(byte_range("bytes=0-", 100), Some((0, 99)));
        assert_eq!(byte_range("bytes=10-19", 100), Some((10, 19)));
        assert_eq!(byte_range("bytes=90-500", 100), Some((90, 99)), "an end past the file is the file's end");
        assert_eq!(byte_range("bytes=-10", 100), Some((90, 99)));
        assert_eq!(byte_range("bytes=100-", 100), None, "past the end: the whole file instead");
        assert_eq!(byte_range("", 100), None);
        assert_eq!(byte_range("bytes=0-", 0), None);
        assert_eq!(pct_decode(&pct_encode("a render: café/1")), "a render: café/1");
    }

    #[test]
    fn through_the_web_proxy_a_key_counts_for_nothing_and_changes_come_from_the_page() {
        let k = "k".repeat(64);
        let w = Who::new(&k, "", "https://midas.example.org", "203.0.113.9, 10.0.0.1", "https", "midas.example.org", "127.0.0.1");
        assert!(w.web && w.principal.is_none() && w.origin_ok && w.https);
        assert_eq!(w.peer, "203.0.113.9", "the person's address, not the proxy's");
        assert!(w.cookie("t", 60).ends_with("; Secure"));
        let elsewhere = Who::new("", "midas_session=abc", "https://evil.example", "1.2.3.4", "https", "midas.example.org", "x");
        assert!(!elsewhere.origin_ok && elsewhere.token.as_deref() == Some("abc"));
        let direct = Who::new("", "a=1; midas_session=t2", "", "", "", "10.44.0.1:4791", "10.44.0.5");
        assert!(!direct.web && direct.origin_ok && !direct.https && direct.token.as_deref() == Some("t2"));
        assert!(!direct.cookie("t", 60).contains("Secure"), "plain http on the tunnel: a Secure cookie would never come back");
    }
}

/// Who may do what through `api`, against a scratch hub state.
#[cfg(test)]
mod roles {
    use super::*;

    fn key(role: &str) -> Who {
        Who { web: false, principal: Some(Principal { caller: format!("{role}-key"), account: None, role: role.into() }),
              token: None, origin_ok: true, https: false, peer: "10.44.0.9".into() }
    }

    fn person(role: &str, from_the_page: bool) -> Who {
        Who { web: true, principal: Some(Principal { caller: "web".into(), account: Some("jo".into()), role: role.into() }),
              token: Some("t".into()), origin_ok: from_the_page, https: true, peer: "203.0.113.9".into() }
    }

    fn nobody(web: bool) -> Who {
        Who { web, principal: None, token: None, origin_ok: true, https: web, peer: "10.44.0.9".into() }
    }

    #[test]
    fn a_persons_archive_ends_an_editors_session_and_a_mirrors_own_does_not() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("archive-route");
        let local = json!({"client": "Zed", "machine": "mini", "cwd": "/x"});
        let id = crate::sessions::attach("w", "w", "3f4a74a9-0255-4b64-9bbf-66d74efa32c2", "t", &local, Some("main"), "p").unwrap()["id"]
            .as_str().unwrap().to_string();
        let path = format!("/v1/hosted/{id}/archive");
        let dones = || crate::sessions::inbox(&id).iter().filter(|i| i["kind"] == "done").count();
        // The mirror archiving it, after Zed did: its key, no "done".
        assert_eq!(status(&key("steer"), "POST", &path, json!({"on": true})), 200);
        assert_eq!(dones(), 0);
        // A person on the page: done, so ended in Zed too.
        assert_eq!(status(&person("steer", true), "POST", &path, json!({"on": true})), 200);
        assert_eq!(dones(), 1);
        // Brought back: nothing to end.
        assert_eq!(status(&person("steer", true), "POST", &path, json!({"on": false})), 200);
        assert_eq!(dones(), 1);
    }

    #[test]
    fn a_path_that_is_only_its_ends_is_answered_not_a_crash() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("bare-paths");
        // Each once sliced past its own start; with panic = "abort" one GET ended the hub.
        for (m, p) in [("GET", "/v1/hosted/log"), ("GET", "/v1/hosted/files"), ("GET", "/v1/nodes/config"),
                       ("GET", "/v1/nodes/midas"), ("POST", "/v1/nodes/register"), ("GET", "/v1/hosted//log")] {
            let _ = status(&nobody(false), m, p, json!({}));
        }
        assert_eq!(inner("nodes/vps-1/config", "nodes/", "/config"), "vps-1");
        assert_eq!(inner("nodes/config", "nodes/", "/config"), "");
        // A `since` chrono cannot subtract: held to what can be.
        for q in ["since=9223372036854775807", "since=-5", "since=100000000000"] {
            let f = events::Filter::from_query(q);
            let _ = events::read_at(&registry::root(), &f);
            let _ = crate::builds::history(since_q(q.strip_prefix("since=").map(str::to_string)));
        }
    }

    #[test]
    fn a_retired_starts_only_key_is_no_key() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        let file = std::env::temp_dir().join(format!("midas-test-callers-{}.json", std::process::id()));
        let (svc, ws) = ("s".repeat(40), "w".repeat(40));
        std::fs::write(&file, json!({
            "podium": {"key": svc, "role": "steer", "starts": ["acme/deck"]},
            "workstation": {"key": ws, "role": "steer"},
        }).to_string()).unwrap();
        // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
        unsafe { std::env::set_var("MIDAS_CALLERS", &file) };
        let (left, kept) = (caller_for(&svc), caller_for(&ws).map(|(n, _)| n));
        unsafe { std::env::remove_var("MIDAS_CALLERS") };
        let _ = std::fs::remove_file(&file);
        assert!(left.is_none(), "without its narrowing it would be a plain steer key");
        assert_eq!(kept.as_deref(), Some("workstation"));
    }

    fn status(who: &Who, method: &str, path: &str, body: Value) -> u16 {
        match api(method, path, "", &body, who, &who.peer, "10.44.0.1:4791") {
            Ok((code, _)) => code,
            Err(_) => 400, // an error inside an allowed handler: allowed, and answered 400
        }
    }

    #[test]
    fn a_projects_settings_on_the_page_are_an_admins_and_its_about_says_how_to_get_it() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("project-page");
        crate::hosted::create(&crate::hosted::New {
            owner: "acme", name: "shop", description: "A shop", public: false, gate: Some("true"), gate_nodes: None, by: "test",
        }).unwrap();
        let set = json!({"repo": "acme/shop", "description": "The shop"});
        assert_eq!(status(&person("steer", true), "POST", "/v1/projects/set", set.clone()), 403, "a steer person may not");
        assert_eq!(status(&person("admin", true), "POST", "/v1/projects/set", set.clone()), 200);
        assert_eq!(status(&key("operator"), "POST", "/v1/projects/set", set), 200, "an agent's project_set, as before");
        let (code, about) = api("GET", "/v1/repos/acme/shop/about", "", &json!({}), &person("viewer", true), "203.0.113.9", "10.44.0.1:4791").unwrap();
        assert_eq!(code, 200);
        assert_eq!((about["description"].as_str(), about["public"].as_bool()), (Some("The shop"), Some(false)));
        assert!(about["ssh"].as_str().is_some_and(|s| s.ends_with("acme/shop.git")) && about["head"]["sha"].is_string(), "{about}");
    }

    #[test]
    fn each_role_may_do_what_it_says_and_no_more() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("roles");
        // What each request needs: open, operator, steer, admin, or a runner's key.
        let requests: [(&str, &str, Value, &str); 29] = [
            ("GET", "/v1/state", json!({}), "open"),
            ("POST", "/v1/claim", json!({"owner": "wt", "machine": "server"}), "operator"),
            ("POST", "/v1/drain", json!({"node": "cpu-1", "why": "test"}), "operator"),
            ("POST", "/v1/hosted/start", json!({"prompt": "hello"}), "steer"),
            ("POST", "/v1/hosted/create", json!({"name": "", "brief": "hello"}), "steer"),
            // A voice conversation kept: steering, as the call is.
            ("POST", "/v1/hosted/talks", json!({"about": {"kind": "nowhere"}}), "steer"),
            // Spends the hub's OpenAI key: steering, as typing to a session is.
            ("POST", "/v1/hosted/discuss", json!({"sdp": "v=0", "instructions": "hi"}), "steer"),
            // A runner's Claude Code reads the code for it: steering too.
            ("POST", "/v1/hosted/discuss/ask", json!({"question": ""}), "steer"),
            ("POST", "/v1/hosted/discuss/answer", json!({"id": "qnone"}), "steer"),
            ("POST", "/v1/hosted/runner/answer", json!({"id": "qnone"}), "runner"),
            ("POST", "/v1/hosted/runner/scouted", json!({"round": "rnone"}), "runner"),
            ("POST", "/v1/hosted/runner/scouting", json!({"round": "rnone"}), "runner"),
            // The research tree changed: steering, as templates are.
            ("POST", "/v1/hosted/tree", json!({"op": "none"}), "steer"),
            ("POST", "/v1/hosted/s99/push", json!({"items": []}), "runner"),
            ("POST", "/v1/hosted/attach", json!({"agent_session": "not-a-uuid"}), "runner"),
            ("POST", "/v1/accounts/role", json!({"name": "nobody", "role": "viewer"}), "admin"),
            ("GET", "/v1/accounts", json!({}), "admin"),
            // The OpenAI key, and how voice discussions go: the workspace's settings.
            ("POST", "/v1/settings/openai_key", json!({"key": "not a key"}), "admin"),
            ("GET", "/v1/settings/models", json!({}), "admin"),
            // The bots' sign-ins and keys.
            ("GET", "/v1/settings/bots", json!({}), "admin"),
            ("POST", "/v1/settings/bot", json!({"name": "bad name"}), "admin"),
            ("POST", "/v1/settings/bot/remove", json!({"name": "nobody"}), "admin"),
            // An agent is a command the runner runs: setting one is admin work.
            ("POST", "/v1/settings/agent", json!({"id": "bad id"}), "admin"),
            ("POST", "/v1/settings/agent/remove", json!({"id": "nobody"}), "admin"),
            ("GET", "/v1/settings/agents", json!({}), "admin"),
            // Its command, for the runner starting a session: may hold a key.
            ("POST", "/v1/hosted/runner/agent", json!({"id": "nobody"}), "runner"),
            ("POST", "/v1/settings/bot/start", json!({"name": "nobody"}), "admin"),
            // What agents learnt: not for a node, nor anyone without a key.
            ("GET", "/v1/memory", json!({}), "operator"),
            ("POST", "/v1/memory", json!({"repo": "acme/midas", "changes": []}), "operator"),
        ];
        let rank = |r: &str| crate::accounts::rank(r).unwrap();
        for (method, path, body, needs) in &requests {
            let may = |who: &Who| ![401, 403].contains(&status(who, method, path, body.clone()));
            // A key, by its role.
            for role in crate::accounts::ROLES {
                let want = match *needs {
                    "open" => true,
                    "runner" => rank(role) >= rank("steer"),
                    n => rank(role) >= rank(n),
                };
                assert_eq!(may(&key(role)), want, "a {role} key, {method} {path}");
            }
            // A person logged in, from the page, by role; never a runner, never from another page.
            for role in crate::accounts::ROLES {
                let want = match *needs {
                    "open" => true,
                    "runner" => false,
                    n => rank(role) >= rank(n),
                };
                assert_eq!(may(&person(role, true)), want, "{role} person, {method} {path}");
                if *needs != "open" {
                    assert!(!may(&person("admin", false)), "a change by cookie from another page: {method} {path}");
                }
            }
            // Nobody: reads on the tunnel only; through the web, not even those.
            assert_eq!(may(&nobody(false)), *needs == "open", "no key, {method} {path}");
            assert!(!may(&nobody(true)), "not logged in, through the web: {method} {path}");
        }
        // An admin's own account is not theirs to demote, reset or remove from the page;
        // another's is, and so is theirs to the CLI's key.
        crate::accounts::add("jo", "admin", "test").unwrap();
        crate::accounts::add("al", "viewer", "test").unwrap();
        for (path, body) in [("/v1/accounts/role", json!({"name": "jo", "role": "viewer"})),
                             ("/v1/accounts/reset", json!({"name": "jo"})), ("/v1/accounts/remove", json!({"name": "jo"}))] {
            assert_eq!(status(&person("admin", true), "POST", path, body), 403, "{path} on one's own account");
        }
        assert_eq!(status(&person("admin", true), "POST", "/v1/accounts/role", json!({"name": "al", "role": "steer"})), 200);
        assert_eq!(status(&key("admin"), "POST", "/v1/accounts/role", json!({"name": "jo", "role": "steer"})), 200);
        // A detached worktree's claim, from a midas that said "HEAD": no branch.
        assert_eq!(status(&key("operator"), "POST", "/v1/claim", json!({"owner": "d", "machine": "laptop", "branch": "HEAD"})), 200);
        assert!(Locked::open().unwrap().leases()["gpu-1"]["branch"].is_null());
    }
}