garage44.eu/jeroen/midas

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

.. /src/sessions.rs

raw

//! Agent sessions midas runs: started, followed and steered from the page, so
//! a person needs neither claude.ai nor a GitHub workspace to work with Claude
//! Code — the repository is the workspace's own, and so are the machines.
//!
//! Three parts, each where it must be:
//!
//! * **The hub keeps them** (`hosted/<id>/` beside the registry): `meta.json`
//!   (title, status, branch, who started it), `log.jsonl` (what the session
//!   said and did, numbered) and `inbox.jsonl` (what the person said to it:
//!   messages, answers to permission requests, cancel, stop). The page reads
//!   the log live over the stream (ws.rs, `follow`); writing to a session takes
//!   the `steer` role, because it is running code.
//! * **A runner runs them** (`midas sessions run`), in the agent container,
//!   where the agent's login is. It asks the hub for sessions to start and for
//!   what was said to its sessions (a long poll), and gives each session a
//!   folder of its own (`session-<id>`, `folder`) with a worktree in it for
//!   each project its agent adds (`add_project`: a branch `session/<id>` off
//!   `origin/<base>`, in a checkout of the project, `checkout`), and an agent
//!   of its own: `MIDAS_AGENT`, an Agent Client Protocol command, Claude
//!   Code's adapter by default. The folder's name is the session's owner name,
//!   and its worktrees are the session's, so it takes nodes and lands like any
//!   session. (Older sessions, and those handed over from an editor, are one
//!   worktree, which is their folder.)
//! * **The page shows them** (a Sessions tab): the list, a new session, and
//!   one session's conversation — its text, its tool calls by title and state,
//!   a permission request with its options, a box to say something, Stop.
//!   File changes are not shown; the branch has them.
//!
//! Permissions are the person's: every `session/request_permission` waits for
//! an answer from the page — or, when they turned the session's autopilot on,
//! from it (autopilot.rs), each decision in the conversation with its reason.
//! Nothing is allowed "always" behind their back.

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::os::unix::fs::MetadataExt;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::sync::{Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

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

use crate::events;
use crate::registry::{self, now};
use crate::store;

/// Every line this module writes to stderr is the runner's log (`runner.log`):
/// timed, to be read against the event log, and never a panic when stderr is gone.
macro_rules! eprintln {
    ($($t:tt)*) => { $crate::util::log_line(&format!($($t)*)) };
}

/// What a session's agent is told about where it runs, beside its own instructions.
const SESSION_BRIEF: &str = "This session was started from the Midas hub page, and the person follows it there, \
often on a phone: they read your text, answer your permission requests, and cannot see your terminal. \
To show them a picture, a sound or a video (a screenshot, a render, a recording), call the midas MCP tool `show` \
with the file's path, or run `midas show <file> --caption \"…\"`; it appears in the conversation, playable there. \
When you ask them to choose (AskUserQuestion), put the option you recommend first, with \"(Recommended)\" at the end of \
its label: the page preselects it. Keep the question itself to a line or two: what you found, the evidence and the \
detail go in your message before it, where they read as formatted text. \
Before any question, and whenever you report a problem you found, write that analysis as one fenced block whose \
language is `analysis`, which the page draws as a panel: `### Problem` (what goes wrong, as seen), `### Evidence` \
(what you ran or read, with numbers, files and lines), `### Cause` (why — or that it is not known yet, and what you \
ruled out), `### Options` (each with what it costs and what it leaves) and `### Recommendation` (which, and why). \
Write it for someone who saw none of your steps: an analysis that fits on one line is not one yet. Ask only for a choice that is theirs and \
changes what you do: carry on by yourself through the steps the task already settles, and never end a step on an \
open \"what next?\" — each one is a round trip from their phone, often hours long. Which part of what they asked \
comes first, and whether to build the next part of it, is not theirs: take the order you recommend, all of it when \
the parts stand apart, and say what you chose — 150 such cards in a month were answered with the recommended \
option or \"doe alles\". Taste (a look, a name, a text), money, data lost and a public service down are theirs. \
When they answer with a question, answer it in your message and end your turn, with no new card. When what was asked is done, \
land it and finish (the finish-branch skill), and before asking whether it shall land, tell them what landing it \
changes, as one fenced block of language `impact`, which the page draws as its own panel: `### What changes` (what \
they and others will see or do differently, step by step as they will meet it, in their words, not the code's), \
`### What stays the same` (what it does not do, and its limits) and `### Before it works` (any step the landing does \
not take: a setting, a key, a deploy, a migration — or that there is none). A wish they add along the way stays in this session when it carries on \
its work — a follow-up, a fix, the same feature shown or told elsewhere (its docs, a slide, another project: add that \
project here) — since the person keeps their focus on one conversation. Only a wish for wholly new functionality, \
unrelated to what this session is for, belongs in a session of its own, and that is rare. Then never start one \
yourself: write a fenced block of language `new-session`, which the page draws as its own panel — `### The wish` \
(their words), `### Why apart` (how it is unrelated to this session's work), `### Builds on` and \
`### Recommendation` — and ask with AskUserQuestion whether to start it (\"Start a new session\" or \"Keep it \
here\"). Only on their yes run `midas sessions start --project <name> \"…\"` (their words, and what it builds on) \
and tell them its id; on \"Keep it here\", do it here. \
When a question concerns another session, name it as midas does — its worktree \
name (bridge-cse_…, session-s3) or an open end's id (t7) — and the page shows them which, linked. \
A deploy you ask for (`midas deploy`) need not be watched: the page shows the person its progress, and when it is \
published or fails, midas leaves you a note, read at your next prompt or tool call. It does not wake you, and \
neither does any other news of midas's own: end your turn rather than wait for one. \
Nothing midas says wakes this session once its turn ends but the time you set: when you promise work for later (\"the rest tomorrow\", spreading \
a task over days), set the time with the midas MCP tool `session_later` (or `midas later --in 4h \"…\"`), saying what \
to do then; midas sends it to you at that time, and the page shows it meanwhile. A clock time the person names is \
theirs: give its offset from UTC, and ask their time zone when the conversation does not say it. \
When you cannot go on until the person does something only they can (paste a token, add a DNS record, register an \
app), never leave it as a sentence at the end of a message, which lists the session as idle, or once landed as \
done: declare it with the midas MCP tool `session_await` (or `midas await \"…\" --steps \"…\"`, with `--secret` for a \
token, whose value then goes to the hub and never to you), and end your turn. The page lists it under Needs you \
until they do it, and midas tells you; when they give it in a reply instead, run `midas await --done`. \
The session's title in their list was taken from its first message: when the work turns to something its title no \
longer says, rename it with the midas MCP tool `session_title` (a few words), without asking.";

/// What an agent in a session's folder is told: where it is, the projects it
/// can work in, and how a session spans them.
fn folder_brief(id: &str, dir: &Path, repos: &[String]) -> String {
    let all = project_names_of_hub();
    let names = |l: &[String]| l.iter().map(|r| r.rsplit('/').next().unwrap_or(r).to_string()).collect::<Vec<_>>().join(", ");
    let now = if repos.is_empty() { "none of them yet".to_string() } else { format!("{} so far, each at ./<name>", names(repos)) };
    format!("\n\nYou run in {}, this session's own folder, which is not a repository. The workspace's projects are {} ({}); \
        this session works in {now}. When the task needs a project's code — to read it, change it or build it — add the project \
        with the midas MCP tool `project_add` (`project: \"<name>\"`, or `midas sessions add-project <name>`): it makes a worktree of it at ./<name>, on \
        branch session/{id} off its main, and links its skills here. A project that does not exist yet is made with `project_create` (the hub hosts it; \
        nobody need set it up by hand), then added. Add as many as the task spans and no more; a question that \
        needs no code needs none. Work in each worktree as in a checkout of its own: read its CLAUDE.md first, commit there, and \
        run builds (`ssh <node> …`, which sends the node the worktree you run it from) and the finish-branch skill from inside it. \
        Each project lands on its own: when a change in one needs a change in another, land the one depended on first, and make \
        each landing stand on its own on main, since one can land while the other is still in review. Before changing a project, \
        `midas who` shows the other sessions working in it and the files they change; agree with them through `midas say`.",
        dir.display(), names(&all), all.join(", "))
}

/// How long the runner's poll may wait for something to do.
#[cfg(not(test))]
const POLL_S: u64 = 20;
/// In tests, a poll with nothing to give does not hold them up.
#[cfg(test)]
const POLL_S: u64 = 1;
/// How long the poll waits between looks when nothing wakes it.
#[cfg(not(test))]
const POLL_IDLE_MS: u64 = 5000;
#[cfg(test)]
const POLL_IDLE_MS: u64 = 400;

// ── The hub's side ───────────────────────────────────────────────────────────

fn root() -> PathBuf {
    registry::root().join("hosted")
}

fn dir(id: &str) -> PathBuf {
    root().join(id)
}

pub(crate) fn id_ok(id: &str) -> bool {
    id.len() <= 12 && id.starts_with('s') && id.len() > 1 && id[1..].bytes().all(|b| b.is_ascii_digit())
}

/// The hosted sessions' lock: every session's meta, the numbering, the deleted
/// list. One lock for all of them, since `poll` changes many metas at once.
fn lock() -> Result<File> {
    store::lock(&root().join(".lock"))
}

fn read_json(p: &Path) -> Value {
    store::read(p).unwrap_or(Value::Null)
}

/// A meta as `read_json` reads it, parsed again only when the file changed. The
/// board, the names and the runner's poll each list every session, and reading
/// and parsing all 500 metas each time was 31 times a minute on the hub. A meta
/// is only ever replaced whole (`store::write_atomic`, a new inode), so a file
/// with the inode, size and times of the one parsed is that one.
fn read_meta(p: &Path) -> Value {
    type Key = (u64, u64, u64, i64, i64, i64, i64);
    fn key(m: &fs::Metadata) -> Key {
        (m.dev(), m.ino(), m.size(), m.mtime(), m.mtime_nsec(), m.ctime(), m.ctime_nsec())
    }
    static PARSED: Mutex<Option<HashMap<PathBuf, (Key, Value)>>> = Mutex::new(None);
    let Ok(now) = fs::metadata(p) else {
        PARSED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default().remove(p);
        return Value::Null;
    };
    if let Some((k, v)) = PARSED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default().get(p) {
        if *k == key(&now) {
            return v.clone();
        }
    }
    // Keyed by what was opened, not by the look before it: a meta replaced in between is read next time.
    let read = File::open(p).and_then(|mut f| {
        let k = key(&f.metadata()?);
        let mut t = String::new();
        f.read_to_string(&mut t)?;
        Ok((k, t))
    });
    let Some((k, v)) = read.ok().and_then(|(k, t)| Some((k, serde_json::from_str::<Value>(&t).ok()?))) else { return Value::Null };
    PARSED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default().insert(p.to_path_buf(), (k, v.clone()));
    v
}

/// Write a session's meta; the caller holds [`lock`].
fn write_meta(id: &str, m: &Value) -> Result<()> {
    store::write_json(&dir(id).join("meta.json"), m, store::PUBLIC)
}

/// Read, change and write a session's meta under the lock, so a change made
/// meanwhile by another thread (the runner's push, the page's archive) is not
/// written over with what was read before it.
fn update_meta<R>(id: &str, f: impl FnOnce(&mut Value) -> R) -> Result<(Value, R)> {
    let _l = lock()?;
    let mut m = meta(id)?;
    let r = f(&mut m);
    write_meta(id, &m)?;
    Ok((m, r))
}

pub fn meta(id: &str) -> Result<Value> {
    if !id_ok(id) {
        bail!("no session {id}");
    }
    let m = read_meta(&dir(id).join("meta.json"));
    if m.is_null() {
        bail!("no session {id}");
    }
    Ok(m)
}

/// The lines of one of a session's files, numbered from 1, after `after`.
fn lines(id: &str, file: &str, after: u64) -> (Vec<Value>, u64) {
    let (items, n, _) = read_from(&dir(id).join(file), 0, 0, after);
    (items, n)
}

/// A file's whole lines from byte `from`, `n` lines being before it: those
/// numbered after `after` built into values, the count, and the byte after the
/// last whole line, where the next read starts. The lines before `after` are
/// only checked to be whole, so they count; building them all, for a log of a
/// megabyte or more, was most of what every follower's look cost.
fn read_from(path: &Path, from: u64, mut n: u64, after: u64) -> (Vec<Value>, u64, u64) {
    let mut buf = Vec::new();
    let read = File::open(path).and_then(|mut f| {
        f.seek(SeekFrom::Start(from))?;
        f.read_to_end(&mut buf)
    });
    if read.is_err() {
        return (Vec::new(), n, from);
    }
    // A line still being written is left for the next read.
    let whole = buf.iter().rposition(|&b| b == b'\n').map_or(0, |i| i + 1);
    let mut out = Vec::new();
    for l in buf[..whole].split(|&b| b == b'\n') {
        if n < after {
            if serde_json::from_slice::<serde::de::IgnoredAny>(l).is_ok() {
                n += 1;
            }
        } else if let Ok(v) = serde_json::from_slice::<Value>(l) {
            n += 1;
            out.push(v);
        }
    }
    (out, n, from + whole as u64)
}

/// How many lines one of a session's files has. Each file's count is kept
/// with where it was taken (the file, its size then), so the next count reads
/// only what was appended since: every agent chunk is an append, and each
/// counted the whole log again.
fn count(id: &str, file: &str) -> u64 {
    static COUNTS: Mutex<BTreeMap<PathBuf, (u64, u64, u64)>> = Mutex::new(BTreeMap::new());
    let path = dir(id).join(file);
    let Ok(md) = fs::metadata(&path) else { return 0 };
    let mut counts = COUNTS.lock().unwrap_or_else(|p| p.into_inner());
    // A file made again (a log cleared) is another inode, or shorter: counted from the start.
    let (from, n) = match counts.get(&path) {
        Some(&(ino, end, n)) if ino == md.ino() && end <= md.len() => (end, n),
        _ => (0, 0),
    };
    let (_, n, end) = read_from(&path, from, n, u64::MAX);
    counts.insert(path, (md.ino(), end, n));
    n
}

fn append(id: &str, file: &str, items: &[Value]) -> Result<u64> {
    let _l = lock()?;
    let mut n = count(id, file);
    let mut f = OpenOptions::new().create(true).append(true).open(dir(id).join(file))?;
    let mut buf = String::new();
    for it in items {
        n += 1;
        let mut it = it.clone();
        it["n"] = json!(n);
        it["at"] = json!(now());
        buf.push_str(&it.to_string());
        buf.push('\n');
    }
    f.write_all(buf.as_bytes())?;
    drop(_l);
    if file == "inbox.jsonl" {
        arrived();
    }
    crate::ws::nudge();
    Ok(n)
}

/// Something for the runners: a message in an inbox, a session to start. Counts
/// up, so a poll that wakes knows whether anything came.
static ARRIVALS: (Mutex<u64>, Condvar) = (Mutex::new(0), Condvar::new());

pub(crate) fn arrived() {
    *ARRIVALS.0.lock().unwrap_or_else(|p| p.into_inner()) += 1;
    ARRIVALS.1.notify_all();
}

/// A mode's id as an agent names one (`default`, `bypassPermissions`): the agent says which it has.
fn model_ok(model: &str) -> Result<&str> {
    if !crate::acp::model_ok(model) {
        bail!("not a model: {model}");
    }
    Ok(model)
}

/// The mode a session starts in when none is chosen: Trusted, which runs without asking.
const DEFAULT_MODE: &str = "bypassPermissions";

fn mode_ok(mode: &str) -> Result<&str> {
    if mode.is_empty() || mode.len() > 40 || !mode.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) {
        bail!("not a mode: {mode}");
    }
    Ok(mode)
}

/// The next session's id; the caller holds [`lock`].
fn next_id() -> Result<String> {
    let seq = read_json(&root().join("seq.json")).as_u64().unwrap_or(0) + 1;
    store::write_atomic(&root().join("seq.json"), seq.to_string().as_bytes(), store::PUBLIC)?;
    Ok(format!("s{seq}"))
}

/// A session that runs elsewhere — in an editor on a workstation, through
/// `midas acp --mirror` — mirrored here, so the page follows it and steers it
/// as it does one of its own. `local` says where (`client`, `machine`, `cwd`,
/// and `repo`, the checkout's repository).
/// Its agent's conversation id names it: an editor that loads the conversation
/// again comes back to the same session, not a new one. Returns its id and how
/// far its inbox goes already, which the mirror does not hear again.
pub fn attach(by: &str, runner: &str, agent_session: &str, title: &str, local: &Value, branch: Option<&str>, owner: &str) -> Result<Value> {
    if !registry::is_uuid(agent_session) {
        bail!("not an agent's session id: {agent_session}");
    }
    // The repository its checkout is (`owner/name`, its origin's), a project or not: a handover needs one.
    let repo = local["repo"].as_str().and_then(|r| crate::mirror::repo_name(r).ok()).map(|r| r.trim_end_matches(".git").to_string())
        .or_else(|| project_of_dir(&project_names(), local["cwd"].as_str()));
    let text = |k: &str| local[k].as_str().filter(|s| !s.is_empty() && s.len() <= 200).map(str::to_string);
    let local = json!({"client": text("client").unwrap_or_else(|| "an editor".into()),
                       "machine": text("machine").unwrap_or_else(|| "?".into()), "cwd": text("cwd")});
    let title: String = title.lines().next().map(str::trim).filter(|l| !l.is_empty()).unwrap_or("A session").chars().take(80).collect();
    let _l = lock()?;
    let again = list().as_array().into_iter().flatten()
        .find(|m| m["agent_session"] == agent_session && m["local"].is_object()).cloned();
    let (id, m) = match again {
        Some(mut m) => {
            let id = m["id"].as_str().unwrap_or("").to_string();
            // Brought back from the runner and in use here again.
            if m["back"].is_object() {
                m["back"]["pending"] = json!(false);
            }
            m["status"] = json!("waiting");
            m["runner"] = json!(runner);
            m["local"] = local;
            m["gone"] = Value::Null;
            if repo.is_some() {
                m["repo"] = json!(repo);
            }
            m["updated"] = json!(now());
            (id, m)
        }
        None => {
            let id = next_id()?;
            fs::create_dir_all(dir(&id))?;
            let m = json!({
                "id": id, "title": title, "prompt": title, "base": null, "branch": branch.unwrap_or(""),
                "owner": owner, "status": "waiting", "by": by, "created": now(), "updated": now(), "active": now(),
                "mode": null, "model": null, "agent_session": agent_session, "runner": runner, "local": local, "repo": repo,
            });
            events::emit("hosted_started", json!({"actor": by, "session": id, "title": title}));
            (id, m)
        }
    };
    write_meta(&id, &m)?;
    events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "waiting"}));
    // On the board, as a session's own hooks would put it there (and a runner puts its own).
    let reason = m["local"]["client"].as_str().unwrap_or("editor").to_lowercase();
    events::emit("session_start", json!({"actor": m["owner"], "branch": m["branch"], "reason": reason, "repo": m["repo"]}));
    events::emit("session_label", json!({"actor": m["owner"], "branch": m["branch"], "label": m["title"]}));
    let inbox = count(&id, "inbox.jsonl");
    Ok(json!({"id": id, "inbox_after": inbox}))
}

/// A session's name from its first message: a brief in Markdown names itself
/// in a `# ` heading on its first line; otherwise its first line that is not a
/// heading (a section's label, `## Goal`, names nothing), its marks stripped.
fn title_of(prompt: &str) -> Option<String> {
    let lines = || prompt.lines().map(str::trim).filter(|l| !l.is_empty());
    let line = match lines().next()?.strip_prefix("# ") {
        Some(named) => named,
        None => lines().find(|l| !l.starts_with('#')).or_else(|| lines().next())?,
    };
    let plain: String = line.trim_start_matches(['#', '>', '-', '*', ' ']).replace(['*', '`'], "").replace("__", "");
    Some(plain.trim().chars().take(80).collect()).filter(|t: &String| !t.is_empty())
}

/// A new session, queued for a runner, in `mode` if one is given (else
/// Trusted, `bypassPermissions`). Returns its id.
///
/// It works in a folder of its own (`FOLDER`), and its projects are worktrees
/// in it, one per repository, all on its branch: `repo` is the one it starts
/// in (`owner/name` or a name; the first project when none is said), and
/// `auto` starts it in none — the agent adds what the task turns out to need
/// (`add_project`), as many as it needs, or none for a question.
#[allow(clippy::too_many_arguments)]
pub fn start(by: &str, prompt: &str, repo: Option<&str>, base: Option<&str>, mode: Option<&str>, model: Option<&str>, agent: Option<&str>, images: &Value) -> Result<String> {
    let prompt = prompt.trim();
    let pictured = images.as_array().is_some_and(|a| !a.is_empty());
    if prompt.is_empty() && !pictured {
        bail!("say what the session is to do");
    }
    let mode = mode_ok(mode.map(str::trim).filter(|m| !m.is_empty()).unwrap_or(DEFAULT_MODE))?;
    let model = model.map(str::trim).filter(|m| !m.is_empty() && *m != "default").map(model_ok).transpose()?;
    let agent = crate::agents::chosen(agent)?;
    let base = base.map(str::trim).filter(|b| !b.is_empty()).unwrap_or("main");
    if !base.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_./".contains(&b)) || base.contains("..") {
        bail!("not a branch name: {base}");
    }
    let names = project_names();
    let auto = repo.map(str::trim) == Some(AUTO_PROJECT);
    let repo = if auto { None } else { project_in(&names, repo)? };
    let id = {
        let _l = lock()?;
        next_id()?
    };
    let title = title_of(prompt).unwrap_or_else(|| "A picture".into());
    queue(&id, by, &title, prompt, repo.as_deref(), base, mode, model, agent.as_deref(), images)?;
    Ok(id)
}

/// Write a new session `id` down as queued (`queued_meta`), `prompt` its first message.
#[allow(clippy::too_many_arguments)]
fn queue(id: &str, by: &str, title: &str, prompt: &str, repo: Option<&str>, base: &str, mode: &str, model: Option<&str>, agent: Option<&str>, images: &Value) -> Result<()> {
    queued_meta(id, by, title, prompt, repo, base, mode, model, agent)?;
    first_message(id, by, title, prompt, images)
}

/// A new session's meta, queued. Takes no lock, so `create` writes it under its own. `agent`
/// is none for Claude Code, so the meta of every session from before there was a choice reads right.
#[allow(clippy::too_many_arguments)]
fn queued_meta(id: &str, by: &str, title: &str, prompt: &str, repo: Option<&str>, base: &str, mode: &str, model: Option<&str>, agent: Option<&str>) -> Result<()> {
    fs::create_dir_all(dir(id))?;
    write_meta(id, &json!({
        "id": id, "title": title, "prompt": prompt, "base": base, "branch": format!("session/{id}"),
        "owner": format!("session-{id}"), "status": "queued", "by": by, "created": now(), "updated": now(), "active": now(),
        "mode": mode, "model": model, "agent": agent, "repo": repo, "repos": repo.iter().collect::<Vec<_>>(), "layout": FOLDER,
    }))
}

/// A new session's first message, in its inbox for the runner (which takes the lock).
fn first_message(id: &str, by: &str, title: &str, prompt: &str, images: &Value) -> Result<()> {
    let images = take_uploads(id, images)?;
    append(id, "inbox.jsonl", &[json!({"kind": "message", "text": prompt, "by": by, "images": images})])?;
    events::emit("hosted_started", json!({"actor": by, "session": id, "title": title, "status": "queued"}));
    Ok(())
}

/// The longest name `create` takes, in characters: what the page's list shows of a title.
pub const NAME_MAX: usize = 80;
/// The longest brief `create` takes, in bytes: a brief, not a document.
pub const BRIEF_MAX: usize = 32 * 1024;

/// Why `create` made no session.
#[derive(Debug, PartialEq)]
pub enum Refused {
    /// The name, brief or base is not one a session can take (HTTP 400).
    Invalid(String),
    /// It would clash with what is there: a session at work by that name, or
    /// its branch in a project already (HTTP 409).
    Conflict(String),
}

impl std::fmt::Display for Refused {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Refused::Invalid(why) | Refused::Conflict(why) => f.write_str(why),
        }
    }
}

/// A new session for tooling (`POST /v1/hosted/create`, `midas sessions
/// create`): `name` its title, `brief` its first message, its branch
/// `session/<id>` off `base` (main) in every project it adds. It starts in no
/// project unless `repo` says one: its agent adds what the work needs.
/// Returns its id, status (`queued` until a runner takes it), branch and its
/// place on the page; or why not, as `Refused`.
pub fn create(by: &str, name: &str, brief: &str, repo: Option<&str>, base: Option<&str>) -> Result<std::result::Result<Value, Refused>> {
    let invalid = |why: String| Ok(Err(Refused::Invalid(why)));
    let name = name.trim();
    let brief = brief.trim();
    if name.is_empty() {
        return invalid("give the session a name".into());
    }
    if name.chars().count() > NAME_MAX {
        return invalid(format!("a name is at most {NAME_MAX} characters; this one is {}", name.chars().count()));
    }
    if name.chars().any(char::is_control) {
        return invalid("a name is one line, without control characters".into());
    }
    if brief.is_empty() {
        return invalid("say in the brief what the session is to do".into());
    }
    if brief.len() > BRIEF_MAX {
        return invalid(format!("a brief is at most {} KB; this one is {} KB", BRIEF_MAX / 1024, brief.len().div_ceil(1024)));
    }
    let base = base.map(str::trim).filter(|b| !b.is_empty()).unwrap_or("main");
    if !base.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_./".contains(&b)) || base.contains("..") {
        return invalid(format!("not a branch name: {base}"));
    }
    let names = project_names();
    let repo = match repo.map(str::trim).filter(|r| !r.is_empty() && *r != AUTO_PROJECT) {
        None => None,
        Some(r) => match project_in(&names, Some(r)) {
            Ok(r) => r,
            Err(e) => return invalid(format!("{e:#}")),
        },
    };
    let mirrors: Vec<(String, PathBuf)> = names.iter().map(|r| (r.clone(), crate::mirror::mirror_path(r))).collect();
    if let Some(r) = &repo {
        let at = crate::mirror::mirror_path(r);
        if at.join("HEAD").exists() && !has_branch(&at, base) {
            return invalid(format!("{r} has no branch {base}"));
        }
    }
    // Its first message names it, as a brief written on the page does.
    let prompt = if brief.starts_with("# ") { brief.to_string() } else { format!("# {name}\n\n{brief}") };
    // Checked, numbered and written down under one lock, so two creates of one name cannot both pass.
    let id = {
        let _l = lock()?;
        if let Some(m) = at_work_named(name) {
            return Ok(Err(Refused::Conflict(format!("{} is at work already as \"{name}\": name this one otherwise, or end that one",
                                                    m["id"].as_str().unwrap_or("a session")))));
        }
        let id = next_id()?;
        let branch = format!("session/{id}");
        if let Some((r, _)) = mirrors.iter().find(|(_, at)| has_branch(at, &branch)) {
            // The id's own branch was left over (a session's record deleted, its branch kept):
            // a new session would carry on that one's work as if it were its own.
            return Ok(Err(Refused::Conflict(format!("{r} has a branch {branch} already, from an earlier session: delete it, or try again for the next id"))));
        }
        queued_meta(&id, by, name, &prompt, repo.as_deref(), base, DEFAULT_MODE, None, None)?;
        id
    };
    first_message(&id, by, name, &prompt, &Value::Null)?;
    let m = meta(&id)?;
    Ok(Ok(json!({"id": id, "status": m["status"], "branch": m["branch"], "base": base, "repo": repo,
                 "title": name, "page": format!("/sessions/{id}"), "api": format!("/v1/hosted/{id}")})))
}

/// The session at work (not ended, finished or archived) called `name`, by any case.
fn at_work_named(name: &str) -> Option<Value> {
    list().as_array()?.iter().find(|m| {
        m["title"].as_str().is_some_and(|t| t.trim().eq_ignore_ascii_case(name))
            && !matches!(m["status"].as_str(), Some("stopped" | "failed"))
            && m["archived"] != true && m["finished"].is_null()
    }).cloned()
}

/// Whether the (bare, mirrored) repository at `repo` has branch `name`; none where there is no repository.
fn has_branch(repo: &Path, name: &str) -> bool {
    repo.join("HEAD").exists()
        && Command::new("git").arg("-C").arg(repo).args(["rev-parse", "-q", "--verify", &format!("refs/heads/{name}")])
            .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())
}

/// The project a new session is said to be in when its agent is to pick its own.
pub const AUTO_PROJECT: &str = "auto";

/// A session's layout: a folder of its own with a worktree per project in it,
/// rather than (before sessions could span projects, and handed over from an
/// editor) one worktree that is the session's folder itself.
const FOLDER: &str = "folder";

/// Whether a session works in a folder of its projects' worktrees (`FOLDER`).
/// One started between `auto` and folders (2026-10-25) names no project and is one too.
fn in_folder(m: &Value) -> bool {
    m["layout"] == FOLDER || (m["auto_project"] == true && m["repo"].is_null())
}

/// The projects a session works in: its folder's, else its one.
pub fn repos_of(m: &Value) -> Vec<String> {
    let listed: Vec<String> = m["repos"].as_array().into_iter().flatten().filter_map(|r| r.as_str().map(str::to_string)).collect();
    if !listed.is_empty() || in_folder(m) {
        return listed;
    }
    m["repo"].as_str().map(|r| vec![r.to_string()]).unwrap_or_default()
}

/// The workspace's projects: the repositories of hub.conf's `repos`, each
/// named by its last segment, and where a runner clones it from. A session is
/// in one (the first when none is said); the nodes are the workspace's, so
/// every project's sessions take the same machines.
pub fn projects() -> Value {
    let conf = crate::conf::hub();
    let git = conf.forgejo_ssh.trim_end_matches('/').to_string();
    json!(project_names().iter().map(|r| {
        // A project the hub hosts is cloned from the hub, by key (hosted.rs).
        let url = if crate::hosted::is_hosted(r) { crate::hosted::url(r) } else { format!("{git}/{r}.git") };
        json!({"repo": r, "name": r.rsplit('/').next(), "git": url, "hosted": crate::hosted::is_hosted(r)})
    }).collect::<Vec<_>>())
}

pub(crate) fn project_names() -> Vec<String> {
    crate::conf::hub().repos.iter().filter_map(|r| crate::mirror::repo_name(r).ok()).map(|r| r.trim_end_matches(".git").to_string()).collect()
}

/// `repo` (`owner/name`, or a project's name alone) as one of the projects
/// `names`, the first when none is said; none when the workspace has none
/// (the runner's own checkout).
/// The project `repo` names (`owner/name`, or its name), or the first when it names none.
pub(crate) fn project_of(repo: Option<&str>) -> Result<Option<String>> {
    project_in(&project_names(), repo)
}

fn project_in(names: &[String], repo: Option<&str>) -> Result<Option<String>> {
    let Some(r) = repo.map(str::trim).filter(|r| !r.is_empty()) else { return Ok(names.first().cloned()) };
    if let Some(n) = names.iter().find(|n| !r.contains('/') && n.rsplit('/').next() == Some(r)) {
        return Ok(Some(n.clone()));
    }
    // A renamed project's old name, from a checkout cloned before (hosted.rs `current`).
    let r = crate::hosted::current(crate::mirror::repo_name(r)?.trim_end_matches(".git"));
    if !names.contains(&r) {
        bail!("{r} is not one of the workspace's projects ({}): add it to the hub's repos (midas hub setup --repo …)", names.join(", "));
    }
    Ok(Some(r))
}

/// The project a checkout at `cwd` is, by its directory's name, for an
/// editor that did not say (a midas from before it did): `…/podium` is
/// `acme/podium` when exactly one project is called that.
fn project_of_dir(names: &[String], cwd: Option<&str>) -> Option<String> {
    let dir = cwd?.trim_end_matches('/').rsplit('/').next().filter(|d| !d.is_empty())?;
    let mut hits = names.iter().filter(|n| n.rsplit('/').next() == Some(dir));
    let one = hits.next()?;
    hits.next().is_none().then(|| one.clone())
}

/// A project for a session: one more of its folder's (its agent adding what
/// the work needs, `add_project`), said in its conversation; or, for a session
/// of one worktree, said on the page where nobody said it before (an editor's
/// from a midas that did not, or one from before there were projects).
pub fn set_project(id: &str, repo: &str, by: &str) -> Result<String> {
    if repo.trim().is_empty() {
        bail!("say which project");
    }
    let names = project_names();
    let Some(repo) = project_in(&names, Some(repo))? else { bail!("the workspace has no projects") };
    let (m, added) = update_meta(id, |m| take_project(m, &repo))?;
    let Some(added) = added else {
        bail!("{id} is in {} already, and works in its one worktree (it began before sessions could span projects)",
              m["repo"].as_str().unwrap_or("a project"));
    };
    if !added {
        return Ok(repo);
    }
    let first = m["repo"] == repo.as_str();
    if in_folder(&m) {
        let name = repo.rsplit('/').next().unwrap_or(&repo);
        let text = if first { format!("working in {name}") } else { format!("working in {name} too") };
        append(id, "log.jsonl", &[json!({"kind": "status", "text": text})])?;
    }
    events::emit("hosted_project", json!({"actor": by, "session": id, "repo": repo}));
    if !first {
        return Ok(repo);
    }
    // The board's card: its project, as a session's start says it.
    events::emit("session_start", json!({"actor": m["owner"], "branch": m["branch"], "reason": "project", "repo": repo}));
    Ok(repo)
}

/// `repo` into a session's meta: one more of a folder's (`Some(false)` when it
/// has it already), the first its `repo` too; a one-worktree session's only
/// while it has none (`None` when it has one).
fn take_project(m: &mut Value, repo: &str) -> Option<bool> {
    if in_folder(m) {
        let mut repos = repos_of(m);
        if repos.iter().any(|r| r == repo) {
            return Some(false);
        }
        repos.push(repo.to_string());
        m["repos"] = json!(repos);
        m["layout"] = json!(FOLDER);
        if m["repo"].is_null() {
            m["repo"] = json!(repo);
        }
        return Some(true);
    }
    let free = m["repo"].is_null();
    if free {
        m["repo"] = json!(repo);
    }
    free.then_some(true)
}

/// Project `from` renamed to `to`, or deleted (`None`), in every session's meta
/// (hosted.rs `rename_in`): the sessions it changed.
pub(crate) fn repo_renamed(from: &str, to: Option<&str>) -> Result<Vec<String>> {
    let _l = lock()?;
    let mut changed = vec![];
    for id in fs::read_dir(root()).into_iter().flatten().flatten().filter_map(|e| e.file_name().to_str().filter(|n| id_ok(n)).map(str::to_string)) {
        let Ok(mut m) = meta(&id) else { continue };
        if crate::hosted::rename_in(&mut m, from, to) {
            write_meta(&id, &m)?;
            changed.push(id);
        }
    }
    Ok(changed)
}

/// Every session, newest first.
pub fn list() -> Value {
    let mut v: Vec<Value> = fs::read_dir(root()).into_iter().flatten().flatten()
        .filter_map(|e| e.file_name().to_str().filter(|n| id_ok(n)).map(str::to_string))
        .filter_map(|id| meta(&id).ok())
        .collect();
    v.sort_by_key(|m| std::cmp::Reverse(m["created"].as_i64().unwrap_or(0)));
    // Moved, not `json!`: that serialises every meta into a copy of itself.
    Value::Array(v)
}

/// What a session said last: its last agent message, for the research tree's
/// Harvest (tree.rs), which reads what finished sessions left open.
pub fn last_words(id: &str) -> Option<String> {
    let (items, _) = lines(id, "log.jsonl", 0);
    items.iter().rev().find(|i| i["kind"] == "agent").and_then(|i| i["text"].as_str()).map(str::to_string)
}

/// What a session cost in dollars, from its usage lines: each agent process counts up from nothing, so a
/// cost lower than the one before it starts a new one, and the session's is the sum of each one's last.
pub fn cost_of(id: &str) -> Option<f64> {
    let (items, _) = lines(id, "log.jsonl", 0);
    let costs = items.iter().filter(|i| i["kind"] == "usage").filter_map(|i| i["cost"].as_f64());
    let (mut total, mut last, mut any) = (0.0, 0.0, false);
    for c in costs {
        if c < last {
            total += last;
        }
        last = c;
        any = true;
    }
    any.then_some(total + last)
}

pub fn log(id: &str, after: u64) -> Result<Value> {
    meta(id)?;
    let (items, next) = lines(id, "log.jsonl", after);
    Ok(json!({"items": items, "next": next}))
}

/// What the person says to a session: `message` (text), `permit` (request,
/// option), `cancel` (the turn), `stop` (the session).
pub fn tell(id: &str, kind: &str, fields: &Value, by: &str) -> Result<()> {
    let m = meta(id)?;
    if matches!(m["status"].as_str(), Some("stopped" | "failed")) {
        bail!("{id} has ended");
    }
    let mut item = json!({"kind": kind, "by": by});
    match kind {
        "message" => {
            let text = fields["text"].as_str().unwrap_or("").trim();
            let images = take_uploads(id, &fields["images"])?;
            let files = take_files(id, &fields["files"])?;
            if text.is_empty() && images.is_empty() && files.is_empty() {
                bail!("say something");
            }
            item["text"] = json!(text);
            if !images.is_empty() {
                item["images"] = json!(images);
            }
            if !files.is_empty() {
                item["files"] = json!(files);
            }
            // Send now: stop what it is doing and take this next, rather than queue it.
            item["now"] = json!(fields["now"] == true);
            // Only midas's own say whose note it is (`collab::page_note`).
            if by == "midas" && fields["note"].is_object() {
                item["note"] = fields["note"].clone();
            }
        }
        "permit" => {
            item["request"] = fields["request"].clone();
            item["option"] = fields["option"].clone();
        }
        "mode" => item["mode"] = json!(mode_ok(fields["mode"].as_str().unwrap_or(""))?),
        // On or off, until when, to what end (autopilot.rs): kept in the meta for the page and a runner
        // that starts again, and in the inbox for the runner running it now.
        "autopilot" => {
            if m["local"].is_object() {
                bail!("{id} runs in an editor; the autopilot answers only sessions a runner here runs");
            }
            let c = crate::autopilot::change(fields)?;
            update_meta(id, |m| m["autopilot"] = crate::autopilot::meta_of(&c, by))?;
            events::emit("hosted_autopilot", json!({"actor": by, "session": id, "on": c["on"]}));
            for k in ["on", "until", "goal"] {
                item[k] = c[k].clone();
            }
        }
        "model" => item["model"] = json!(model_ok(fields["model"].as_str().unwrap_or(""))?),
        "queue" => {
            let op = fields["op"].as_str().unwrap_or("");
            if !matches!(op, "remove" | "edit" | "move" | "clear" | "now") {
                bail!("a queue op is remove, edit, move, clear or now");
            }
            item["op"] = json!(op);
            if op != "clear" {
                item["qid"] = json!(fields["qid"].as_u64().context("which message (qid)?")?);
            }
            if op == "edit" {
                let text = fields["text"].as_str().unwrap_or("").trim();
                if text.is_empty() || text.len() > 64 * 1024 {
                    bail!("an edit is some words, at most 64 KB");
                }
                item["text"] = json!(text);
            }
            if op == "move" {
                item["to"] = json!(fields["to"].as_u64().context("to where (to)?")?);
            }
        }
        "answer" => {
            item["request"] = fields["request"].clone();
            item["action"] = json!(match fields["action"].as_str() { Some("accept") => "accept", Some("decline") => "decline", _ => "cancel" });
            if fields["content"].to_string().len() > 32 * 1024 {
                bail!("an answer of at most 32 KB");
            }
            item["content"] = if fields["content"].is_object() { fields["content"].clone() } else { json!({}) };
        }
        "cancel" | "stop" => {}
        // To the hub's runner, from the editor it runs in; and back.
        "handoff" => {
            if !m["local"].is_object() {
                bail!("{id} runs here already");
            }
            if !registry::is_uuid(m["agent_session"].as_str().unwrap_or("")) {
                bail!("{id}'s agent gave no conversation id to carry over");
            }
            // Refused here, before the editor closes anything: a runner can only go on in a project it has.
            let names = project_names();
            if !names.is_empty() {
                // Its editor's word, else the page's, else its checkout's name.
                let said = fields["repo"].as_str().filter(|r| !r.trim().is_empty());
                let repo = match m["repo"].as_str().or(said) {
                    Some(r) => project_in(&names, Some(r))?,
                    None => project_of_dir(&names, m["local"]["cwd"].as_str()),
                };
                let Some(repo) = repo else {
                    bail!("{id}'s editor did not say which project it is in: choose one on its page ({})", names.join(", "))
                };
                if m["repo"].is_null() {
                    update_meta(id, |m| m["repo"] = json!(repo))?;
                }
            }
        }
        "handback" => {
            if !m["handed"].is_object() || m["local"].is_object() {
                bail!("{id} did not come from an editor");
            }
        }
        // Archived on the page while its editor has it: ended there too (tap.rs).
        "done" => {
            if !m["local"].is_object() {
                bail!("{id} runs here, not in an editor");
            }
        }
        _ => bail!("a session hears message, permit, answer, mode, model, autopilot, queue, cancel, stop, handoff, handback or done"),
    }
    if matches!(kind, "handoff" | "handback") {
        update_meta(id, |m| m[format!("{kind}_by")] = json!(by))?;
    }
    append(id, "inbox.jsonl", &[item.clone()])?;
    // A decision the person made, into their focus ledger (focus.rs).
    if let Some(person) = crate::focus::person_of(by) {
        match kind {
            "permit" | "answer" => {
                let (asked, before) = asked_in_log(id, item["request"].as_str().unwrap_or(""));
                let custom = item["content"].as_object().is_some_and(|c| c.iter().any(|(k, v)| k.ends_with("_custom") && v.as_str().is_some_and(|t| !t.trim().is_empty())));
                let answer = if kind == "permit" { item["option"].clone() } else { item["content"].clone() };
                let kind = if kind == "permit" { "permission" } else { "question" };
                crate::focus::record(person, id, kind, asked.as_ref(), &before, &answer, custom, 0);
            }
            "message" => {
                let text = item["text"].as_str().unwrap_or("");
                crate::focus::record(person, id, "message", None, "", &json!(crate::util::short(text, 400)), true, text.len());
            }
            _ => {}
        }
    }
    Ok(())
}

/// The question or permission request `request` in a session's log, and what
/// the session said just before it: what the person read to answer it.
fn asked_in_log(id: &str, request: &str) -> (Option<Value>, String) {
    let items = last_lines(&dir(id).join("log.jsonl"), 512 << 10);
    let Some(i) = items.iter().rposition(|it| matches!(it["kind"].as_str(), Some("question" | "permission")) && it["request"] == request) else {
        return (None, String::new());
    };
    let before = items[..i].iter().rev().take_while(|it| it["kind"] != "user").filter(|it| it["kind"] == "agent")
        .filter_map(|it| it["text"].as_str()).collect::<Vec<_>>();
    (Some(items[i].clone()), before.into_iter().rev().collect::<Vec<_>>().join("\n"))
}

/// A status change that starts or ends a turn: into or out of working (or
/// asking for a permission in the middle of one).
fn turn_edge(from: &str, to: &str) -> bool {
    let in_turn = |s: &str| matches!(s, "working" | "needs_permission");
    in_turn(from) || in_turn(to)
}

/// When the session last did something: its last turn's start or end, or when
/// it was made. This is not `updated`, which is when its status last changed:
/// a runner that starts again reopens every session it ran (`take_back`),
/// which moves `updated` — the stuck-start warning and the poll's give-again
/// need it to — but is not the session doing anything. Every idle clock (the
/// page's "idle 2d", `finish_sweep`) reads this one. Sessions from before it
/// was kept are given it from their log (`backfill_active`).
pub fn active_of(m: &Value) -> Option<i64> {
    m["active"].as_i64().or(m["updated"].as_i64())
}

/// Log items that are the session at work, not the runner's own notes about it
/// (status lines, the modes and models offered when it loads again).
fn did_something(it: &Value) -> bool {
    matches!(it["kind"].as_str(), Some("user" | "agent" | "tool" | "tool_update" | "plan" | "turn_end" | "permission"
        | "permission_answered" | "question" | "answered" | "media"))
}

/// Sessions from before `active` was kept get it once, from their log.
fn backfill_active() {
    for m in list().as_array().into_iter().flatten().filter(|m| m["active"].is_null() && m["imported"].is_null()) {
        let Some(id) = m["id"].as_str() else { continue };
        let (log, _) = lines(id, "log.jsonl", 0);
        let last = log.iter().rev().find(|i| did_something(i)).and_then(|i| i["at"].as_i64()).or(m["created"].as_i64());
        let _ = update_meta(id, |m| {
            if m["active"].is_null() {
                m["active"] = json!(last);
            }
        });
    }
}

/// The runner's report: items for the log, and the session's status now.
pub fn push(id: &str, items: &[Value], status: Option<&str>, runner: &str, agent_session: Option<&str>, queue: Option<&Value>) -> Result<u64> {
    let m = meta(id)?;
    // A session that changed hands hears its status from the side that has it
    // now: what the other says late (it ended, it waits) is no longer true.
    let moved = m["local"].is_object() || m["handed"].is_object();
    let status = status.filter(|_| !(moved && m["runner"].as_str().is_some_and(|r| r != runner)));
    let n = if items.is_empty() { count(id, "log.jsonl") } else { append(id, "log.jsonl", items)? };
    // The autopilot's answers, into the person's focus ledger: what it decided for them (focus.rs).
    let first = n + 1 - items.len() as u64;
    for (i, it) in items.iter().enumerate().filter(|(_, it)| it["by"] == crate::autopilot::BY) {
        if matches!(it["kind"].as_str(), Some("permission_answered" | "answered" | "user")) {
            let (asked, before) = match it["request"].as_str() {
                Some(r) => asked_in_log(id, r),
                None => (None, String::new()),
            };
            crate::focus::record_pilot(&m, it, first + i as u64, asked.as_ref(), &before);
        }
    }
    // Its autopilot deciding, leaving something to the person, or turning itself off: the page and the push say so.
    if m["autopilot"]["on"] == true && !items.is_empty() {
        let _l = lock()?;
        let mut m = meta(id)?;
        if crate::autopilot::follow(&mut m["autopilot"], items) {
            write_meta(id, &m)?;
        }
    }
    // The agent's own id for the conversation: what a reopen loads.
    let new_agent = agent_session.filter(|a| m["agent_session"] != *a);
    // What waits for the agent, as the runner has it: the page shows it and edits it.
    let new_queue = queue.filter(|q| q.is_array() && m["queue"] != **q);
    if status.is_some_and(|s| m["status"] != s) || new_agent.is_some() || new_queue.is_some() {
        let _l = lock()?;
        // Again under the lock: the page may have changed it since (archived it).
        let mut m = meta(id)?;
        if let Some(a) = new_agent {
            m["agent_session"] = json!(a);
        }
        if let Some(q) = new_queue {
            m["queue"] = q.clone();
            if status.is_none_or(|s| m["status"] == s) {
                // The board's cue (a status change makes its own).
                events::emit("hosted_queue", json!({"actor": m["owner"], "session": id, "waiting": q.as_array().map_or(0, Vec::len)}));
            }
        }
        if let Some(s) = status.filter(|s| m["status"] != *s) {
            // A turn beginning or ending is the session doing something (`active`); starting
            // again after a restart, which only goes queued → starting → waiting, is not.
            if turn_edge(m["status"].as_str().unwrap_or(""), s) {
                m["active"] = json!(now());
            }
            m["status"] = json!(s);
            m["updated"] = json!(now());
            m["runner"] = json!(runner);
            // Into the log, which is also what makes the board look again.
            events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": s}));
            // An editor's session leaves the board when it ends there (a runner says so itself).
            if m["local"].is_object() && matches!(s, "stopped" | "failed") {
                events::emit("session_end", json!({"actor": m["owner"], "reason": s}));
            }
        }
        write_meta(id, &m)?;
    }
    Ok(n)
}

/// The largest transcript a session takes from one machine to another.
pub const TRANSCRIPT_MAX: usize = 512 << 20;

fn transcript_of(id: &str) -> PathBuf {
    dir(id).join("transcript.jsonl")
}

/// A session's agent's own transcript, as it left one machine for the next
/// (the agent's conversation itself, not the log): readable by the hub alone.
pub fn put_transcript(id: &str, bytes: &[u8]) -> Result<()> {
    meta(id)?;
    if bytes.len() > TRANSCRIPT_MAX {
        bail!("a transcript of at most {} MB", TRANSCRIPT_MAX >> 20);
    }
    store::write_atomic(&transcript_of(id), bytes, store::PRIVATE)
}

/// Where a session's carried transcript is, if it has one.
pub fn transcript_path(id: &str) -> Option<PathBuf> {
    let p = transcript_of(id);
    (id_ok(id) && p.is_file()).then_some(p)
}

/// The editor's side has handed the session over (tap.rs): its transcript is
/// here, its work on `session/<id>` at `sha`. It is a session the runner
/// runs from now on, loading the conversation in a worktree of that branch.
pub fn handed(id: &str, sha: &str, uncommitted: bool) -> Result<()> {
    if transcript_path(id).is_none() {
        bail!("{id}: send its transcript first");
    }
    let inbox = count(id, "inbox.jsonl");
    // In the mode and on the model it was in there.
    let (mode, model) = last_mode_model(id);
    let (m, ()) = update_meta(id, |m| {
        let branch = format!("session/{id}");
        if let Some(x) = mode {
            m["mode"] = x;
        }
        if let Some(x) = model.filter(|x| x != "default") {
            m["model"] = x;
        }
        m["handed"] = json!({"from": m["local"], "owner": m["owner"], "branch": m["branch"], "runner": m["runner"],
                             "by": m["handoff_by"], "at": now(), "sha": sha, "uncommitted": uncommitted});
        m["local"] = Value::Null;
        m["back"] = Value::Null;
        m["base"] = json!(branch);
        m["branch"] = json!(branch);
        m["owner"] = json!(format!("session-{id}"));
        // No runner has it yet: what the editor's side says late is not heard (`push`).
        m["runner"] = json!("");
        m["status"] = json!("queued");
        m["reopen"] = json!(true);
        m["inbox_after"] = json!(inbox);
        m["transcript_at"] = json!(now());
        m["updated"] = json!(now());
    })?;
    let from = &m["handed"]["from"];
    append(id, "log.jsonl", &[json!({"kind": "status", "text": format!("handed over from {} on {}{}; its work goes on branch {}",
        from["client"].as_str().unwrap_or("the editor"), from["machine"].as_str().unwrap_or("?"),
        m["handed"]["by"].as_str().map(|b| format!(" by {b}")).unwrap_or_default(), m["branch"].as_str().unwrap_or("?"))})])?;
    events::emit("session_end", json!({"actor": m["handed"]["owner"], "reason": "handed over"}));
    events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "queued", "handed": true}));
    arrived();
    Ok(())
}

/// The runner has handed the session back to the editor it came from: its
/// transcript is here, its work on its branch at `sha`. It ends here, and the
/// editor's side brings it back when the session is opened there again.
pub fn handed_back(id: &str, sha: &str) -> Result<()> {
    if transcript_path(id).is_none() {
        bail!("{id}: send its transcript first");
    }
    let (m, ()) = update_meta(id, |m| {
        let h = m["handed"].clone();
        m["back"] = json!({"sha": sha, "branch": m["branch"], "at": now(), "by": m["handback_by"], "pending": true});
        m["local"] = h["from"].clone();
        m["owner"] = h["owner"].clone();
        m["branch"] = h["branch"].clone();
        m["runner"] = h["runner"].clone();
        m["status"] = json!("stopped");
        m["transcript_at"] = json!(now());
        m["updated"] = json!(now());
    })?;
    append(id, "log.jsonl", &[json!({"kind": "status", "text": format!("handed back to {} on {}: open it there to go on",
        m["local"]["client"].as_str().unwrap_or("the editor"), m["local"]["machine"].as_str().unwrap_or("?"))})])?;
    events::emit("session_end", json!({"actor": format!("session-{id}"), "reason": "handed back"}));
    events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "stopped", "handed_back": true}));
    Ok(())
}

/// The mode and the model a session was last in, from its log: what it goes
/// on in when it starts again, here or on another machine.
fn last_mode_model(id: &str) -> (Option<Value>, Option<Value>) {
    let (log, _) = lines(id, "log.jsonl", 0);
    let last = |kind: &str| log.iter().rev().find(|i| i["kind"] == kind).and_then(|i| i["current"].as_str()).map(|c| json!(c));
    (last("mode"), last("model"))
}

/// Start an ended session again — or one whose runner went — in its own worktree,
/// its agent loading the conversation it had (`session/load`). What was said to it
/// before is not said again: the runner starts reading its inbox from here.
/// A runner that started again takes back what it was running: one it was
/// still starting goes back in line as it was (a fresh start, or the reopen
/// it was in), any other is reopened to load its conversation. Without this a
/// runner that died mid-start left its session "starting" for good (s3,
/// 2026-10-21), since `reopen` refuses one that is starting.
pub fn take_back(id: &str, runner: &str, by: &str) -> Result<()> {
    let m = meta(id)?;
    if m["runner"] != runner {
        bail!("{id} is not {runner}'s to take back");
    }
    // Its autopilot gets back the time its runner was away: on 2026-11-19 six, on until midnight,
    // ran out unused while the runner was down for nine hours.
    if let Some(since) = crate::runners::away_since(runner) {
        let until = m["autopilot"]["until"].as_i64().filter(|u| m["autopilot"]["on"] == true && *u > since);
        if let Some(until) = until {
            let away = now() - since;
            update_meta(id, |m| m["autopilot"]["until"] = json!(until + away))?;
            append(id, "log.jsonl", &[json!({"kind": "status",
                "text": format!("its autopilot gets back the {} its runner was away", crate::stats::dur(away as f64))})])?;
        }
    }
    let m = meta(id)?;
    if m["status"] != "starting" {
        // In the middle of a turn: the turn went with the runner, and nothing says so
        // unless it is said. The agent hears it once its conversation is back (`run_session`).
        let mid = matches!(m["status"].as_str(), Some("working" | "needs_permission"));
        reopen_as(id, by, "its runner started again", false)?;
        if mid {
            update_meta(id, |m| m["cut_off"] = json!(true))?;
            append(id, "log.jsonl", &[json!({"kind": "status", "text": "its turn was cut off when its runner stopped: it is told so, to carry on"})])?;
        }
        return Ok(());
    }
    let (m, ()) = update_meta(id, |m| {
        m["status"] = json!("queued");
        m["updated"] = json!(now());
    })?;
    append(id, "log.jsonl", &[json!({"kind": "status", "text": "starting again: its runner started again"})])?;
    events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "queued", "reopened_by": by}));
    arrived();
    Ok(())
}

pub fn reopen(id: &str, by: &str, why: &str) -> Result<()> {
    reopen_as(id, by, why, true)
}

/// Reopened by a person (`asked`), which is the session in use again, or by its
/// runner starting again, which is not: that one keeps its `active`, so a session
/// idle for days does not read as fresh after every deploy.
fn reopen_as(id: &str, by: &str, why: &str, asked: bool) -> Result<()> {
    let m = meta(id)?;
    if matches!(m["status"].as_str(), Some("queued" | "starting")) {
        bail!("{id} is starting already");
    }    // Its agent's conversation is on the machine it was imported from, not a runner's.
    if m["imported"].is_object() {
        bail!("{id} was imported from {}: a record to read, which no runner can load", m["imported"]["from"].as_str().unwrap_or("elsewhere"));
    }
    // One mirrored from an editor has its conversation and its work there, not here.
    if m["local"].is_object() {
        bail!("{id} runs in {} on {}: open it there again", m["local"]["client"].as_str().unwrap_or("an editor"),
              m["local"]["machine"].as_str().unwrap_or("its machine"));
    }
    let inbox = count(id, "inbox.jsonl");
    let (mode, model) = last_mode_model(id);
    let last_mode = mode.unwrap_or_else(|| m["mode"].clone());
    let last_model = model.unwrap_or_else(|| m["model"].clone());
    let (m, ()) = update_meta(id, |m| {
        m["mode"] = last_mode;
        m["model"] = last_model;
        m["status"] = json!("queued");
        m["reopen"] = json!(true);
        m["cut_off"] = Value::Null;
        m["inbox_after"] = json!(inbox);
        m["updated"] = json!(now());
        if asked {
            m["active"] = json!(now());
        }
        // Finished, it is at work again: back in the list until it finishes again.
        m["finished"] = Value::Null;
        m["archived"] = json!(false);
    })?;
    if let Some(owner) = m["owner"].as_str() {
        let _ = crate::collab::set_archived(owner, false, by);
    }
    append(id, "log.jsonl", &[json!({"kind": "status", "text": format!("reopened by {by}{}", if why.is_empty() { String::new() } else { format!(": {why}") })})])?;
    events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "queued", "reopened_by": by}));
    arrived();
    Ok(())
}

/// Archived: kept whole, out of the list's way; the page shows them on asking.
pub fn set_archived(id: &str, on: bool) -> Result<()> {
    update_meta(id, |m| m["archived"] = json!(on)).map(|_| ())
}

/// A new name for a session, when what it is about has changed: its list's
/// title and its board card's label. One line, as a title is made at the start.
/// Which template (and schedule) a session was started from (templates.rs), for the page to say.
pub fn set_template(id: &str, origin: &Value) -> Result<()> {
    update_meta(id, |m| m["template"] = origin.clone())?;
    Ok(())
}

/// Which tech of the research tree a session researches, and the goal and theme it serves (tree.rs
/// `origin_of`), for the lists to put it under its tech.
pub fn set_research(id: &str, origin: &Value) -> Result<()> {
    update_meta(id, |m| m["research"] = origin.clone())?;
    Ok(())
}

/// The session `id` was started from (`midas sessions start` in a session's worktree): the line the
/// Map draws between them (graph.rs, projectmap.tsx). Only a session that exists, and never itself.
pub fn set_from(id: &str, from: &str) -> Result<()> {
    if !id_ok(from) || from == id || meta(from).is_err() {
        return Ok(());
    }
    update_meta(id, |m| m["from"] = json!(from))?;
    Ok(())
}

pub fn set_title(id: &str, title: &str, by: &str) -> Result<String> {
    let Some(title) = title_of(title) else { bail!("say what to call it") };
    let (m, _) = update_meta(id, |m| m["title"] = json!(title))?;
    events::emit("hosted_renamed", json!({"actor": by, "session": id, "title": title}));
    events::emit("session_label", json!({"actor": m["owner"], "branch": m["branch"], "label": title}));
    Ok(title)
}

/// This session's own new name (the agent's `session_title` tool), through the hub.
pub fn rename_self(title: &str) -> Result<String> {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_default();
    let Some(id) = owner.strip_prefix("session-").filter(|i| id_ok(i)) else {
        bail!("only a session on the Midas hub page has a title there; this one is {}",
              if owner.is_empty() { "not one" } else { &owner })
    };
    let v = crate::client::post(&format!("/v1/hosted/{id}/title"), &json!({"title": title}))?;
    Ok(format!("renamed: {}", v["title"].as_str().unwrap_or(title)))
}

// ── Carrying on later ────────────────────────────────────────────────────────
//
// A session that says "I'll do the rest tomorrow" has nothing to wake it then:
// nothing wakes an idle session from outside but midas. So a session keeps one
// time to carry on (`wake`: when, what to do, who set it), set by its agent
// (`midas later`, the `session_later` tool) or on the page, and moved or
// cancelled there. When it is due, the hub's watch tells the session what it
// was to do, reopening it first if it had ended. Work spread over days is a
// chain of these, each turn setting the next, so the page always shows one.
// A session with a time set is neither finished for being idle nor asked
// whether to finish.

/// How far ahead a session may set itself to carry on.
const WAKE_MAX_S: i64 = 30 * 86400;

/// When to carry on, as seconds since the epoch: `after` a while from `t`
/// (`90m`, `4h`, `1d12h`), or `at` a time — RFC 3339 with its offset
/// (`2026-10-30T09:00:00+01:00`, seconds optional) or seconds since the epoch.
pub fn when_of(at: Option<&str>, after: Option<&str>, t: i64) -> Result<i64> {
    match (at.map(str::trim).filter(|s| !s.is_empty()), after.map(str::trim).filter(|s| !s.is_empty())) {
        (Some(_), Some(_)) => bail!("say when (at) or how long from now (in), not both"),
        (None, None) => bail!("say when to carry on: at a time (2026-10-30T09:00+01:00) or in a while (4h, 1d)"),
        (None, Some(d)) => {
            // Parts, largest first: 1d12h is a day and a half.
            let mut s = 0u64;
            let mut rest = d;
            while !rest.is_empty() {
                let end = rest.find(|c: char| c.is_ascii_alphabetic()).map_or(rest.len(), |i| i + 1);
                s += crate::util::seconds(&rest[..end]).filter(|_| end > 1 && rest[..end].ends_with(['m', 'h', 'd']))
                    .with_context(|| format!("a while is minutes, hours or days (90m, 4h, 1d12h), not {d:?}"))?;
                rest = &rest[end..];
            }
            Ok(t + s as i64)
        }
        (Some(a), None) => {
            if let Ok(n) = a.parse::<i64>() {
                return Ok(n);
            }
            let a = a.replacen(' ', "T", 1);
            chrono::DateTime::parse_from_rfc3339(&a)
                .or_else(|_| chrono::DateTime::parse_from_str(&a, "%Y-%m-%dT%H:%M%:z"))
                .map(|d| d.timestamp())
                .map_err(|_| anyhow!("a time is a date, a clock time and its offset from UTC (2026-10-30T09:00+01:00), not {a:?}"))
        }
    }
}

/// Set when session `id` carries on, and what it is to do then; one time per
/// session, so a second replaces the first.
pub fn set_wake(id: &str, at: i64, text: &str, by: &str) -> Result<Value> {
    let m = meta(id)?;
    if m["imported"].is_object() {
        bail!("{id} was imported: a record, which nothing can wake");
    }
    if m["local"].is_object() {
        bail!("{id} runs in an editor, which midas cannot start again");
    }
    let text = text.trim();
    if text.is_empty() || text.len() > 4096 {
        bail!("say what it is to do then, in at most 4 KB");
    }
    let t = now();
    if at <= t {
        bail!("that time has passed");
    }
    if at > t + WAKE_MAX_S {
        bail!("at most 30 days ahead");
    }
    let wake = json!({"at": at, "text": text, "by": by, "set": t});
    update_meta(id, |m| m["wake"] = wake.clone())?;
    append(id, "log.jsonl", &[json!({"kind": "wake", "when": at, "text": text, "by": by})])?;
    events::emit("hosted_wake", json!({"actor": by, "session": id, "at": at}));
    Ok(wake)
}

/// No time to carry on any more: the work is done, or the person said so.
pub fn clear_wake(id: &str, by: &str) -> Result<()> {
    let (_, had) = update_meta(id, |m| std::mem::take(&mut m["wake"]))?;
    if had.is_null() {
        bail!("{id} has no time set to carry on");
    }
    append(id, "log.jsonl", &[json!({"kind": "wake", "cancelled": true, "by": by})])?;
    events::emit("hosted_wake", json!({"actor": by, "session": id, "cancelled": true}));
    Ok(())
}

/// Carry on now: the time has come, or the person would not wait for it. The
/// time is taken off first, so a failure is said once rather than every sweep.
pub fn wake(id: &str, by: &str) -> Result<()> {
    let (m, w) = update_meta(id, |m| std::mem::take(&mut m["wake"]))?;
    let Some(text) = w["text"].as_str() else { bail!("{id} has no time set to carry on") };
    append(id, "log.jsonl", &[json!({"kind": "wake", "woken": true, "by": by})])?;
    events::emit("hosted_wake", json!({"actor": by, "session": id, "woken": true}));
    let woken = (|| {
        if matches!(m["status"].as_str(), Some("stopped" | "failed")) {
            reopen(id, by, "to carry on as planned")?;
        }
        let set = w["set"].as_i64().and_then(|s| chrono::DateTime::from_timestamp(s, 0))
            .map_or(String::new(), |d| format!(" on {}", d.format("%Y-%m-%d %H:%M UTC")));
        let text = format!("From midas: you set this session{set} to carry on now{}. What you were to do then:\n\n{text}",
            if by == "midas" { String::new() } else { format!(" ({by} said to start at once)") });
        tell(id, "message", &json!({"text": text}), "midas")
    })();
    if let Err(e) = &woken {
        let _ = append(id, "log.jsonl", &[json!({"kind": "status", "text": format!("could not carry on as planned: {e:#}")})]);
    }
    woken
}

/// This session's own time to carry on (`midas later`, the `session_later`
/// tool), through the hub: set, or cancelled.
pub fn later_self(at: Option<&str>, after: Option<&str>, text: Option<&str>, cancel: bool) -> Result<String> {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_default();
    let Some(id) = owner.strip_prefix("session-").filter(|i| id_ok(i)) else {
        bail!("only a session on the Midas hub page can be woken later; this one is {}",
              if owner.is_empty() { "not one" } else { &owner })
    };
    if cancel {
        // Nothing to cancel is what the caller wanted, not a failure.
        return match crate::client::post(&format!("/v1/hosted/{id}/wake"), &json!({"cancel": true})) {
            Ok(_) => Ok("cancelled: this session has no time set to carry on".into()),
            Err(e) if format!("{e:#}").contains("no time set") => Ok("this session had no time set to carry on".into()),
            Err(e) => Err(e),
        };
    }
    let v = crate::client::post(&format!("/v1/hosted/{id}/wake"), &json!({"at": at, "in": after, "text": text}))?;
    let at = v["wake"]["at"].as_i64().unwrap_or(0);
    let when = chrono::DateTime::from_timestamp(at, 0).map_or(at.to_string(), |d| d.format("%Y-%m-%d %H:%M UTC").to_string());
    Ok(format!("this session carries on at {when} ({:.1}h from now); the page shows it. Set it again to move it.",
        (at - now()) as f64 / 3600.0))
}

// ── Waiting on the person ────────────────────────────────────────────────────
//
// A session that cannot go on until the person does something only they can —
// paste a token, add a DNS record, register an OAuth app — said so in a
// sentence at the end of a message, and its turn ended: idle, and once landed,
// filed under "Landed today" with the work it waited on undone and nowhere
// listed. So it says so to midas (`awaits`: what, the steps, and where a secret
// goes), set by its agent (`midas await`, the `session_await` tool), and the
// page lists it under Needs you until it is given, put off ("tomorrow"), or
// declined. It is declared, never guessed: "Your turn" painted every recently
// idle session as asking, and read as asking (2026-10-27). One per session; a
// second replaces the first.
//
// A secret it waits for goes from the page to where it is used, never through
// the conversation: a remote MCP server's token (remote.rs) or a bot's
// (botsecrets.rs). The session hears only that it is set.

/// Where a secret the session waits for goes: `remote:<name>` (a remote MCP
/// server's token, at `url` or the one it has) or `bot:<target>:<NAME>`.
pub fn secret_of(spec: &str, url: Option<&str>) -> Result<Value> {
    let url = url.map(str::trim).filter(|u| !u.is_empty());
    match spec.trim().split(':').collect::<Vec<_>>()[..] {
        ["remote", name] if !name.is_empty() => {
            if url.is_none() && !crate::remote::known(name) {
                bail!("remote {name:?} is not set up on the hub: say its endpoint (--url https://…/mcp)");
            }
            Ok(json!({"kind": "remote", "name": name, "url": url}))
        }
        ["bot", target, name] if !target.is_empty() && crate::bot::env_name_ok(name) => Ok(json!({"kind": "bot", "target": target, "name": name})),
        _ => bail!("a secret goes to remote:<name> (a remote MCP server's token) or bot:<node or group>:<NAME>, not {spec:?}"),
    }
}

/// Wait on the person for `text`, with the `steps` to it and, when it is a
/// secret, where that goes (`secret_of`).
pub fn set_awaits(id: &str, text: &str, steps: &str, secret: &Value, by: &str) -> Result<Value> {
    let m = meta(id)?;
    if m["imported"].is_object() || m["finished"].is_object() {
        bail!("{id} is not at work");
    }
    let (text, steps) = (text.trim(), steps.trim());
    if text.is_empty() || text.len() > 300 {
        bail!("say what it waits for, in a line (at most 300 bytes)");
    }
    if steps.len() > 4096 {
        bail!("the steps in at most 4 KB");
    }
    let awaits = json!({"text": text, "steps": steps, "secret": secret, "by": by, "at": now()});
    update_meta(id, |m| m["awaits"] = awaits.clone())?;
    append(id, "log.jsonl", &[json!({"kind": "awaits", "text": text, "by": by})])?;
    events::emit("hosted_awaits", json!({"actor": by, "session": id, "set": true}));
    Ok(awaits)
}

/// It no longer waits: given (`given`), declined by the person (`declined`),
/// or the agent says it has what it needed (`done`).
pub fn clear_awaits(id: &str, how: &str, by: &str) -> Result<Value> {
    let (_, had) = update_meta(id, |m| std::mem::take(&mut m["awaits"]))?;
    if had.is_null() {
        bail!("{id} waits on nothing");
    }
    append(id, "log.jsonl", &[json!({"kind": "awaits", "text": had["text"], "how": how, "by": by})])?;
    events::emit("hosted_awaits", json!({"actor": by, "session": id, "how": how}));
    Ok(had)
}

/// Put off until `until`: it leaves Needs you until then, and comes back with a push.
pub fn snooze_awaits(id: &str, until: i64, by: &str) -> Result<()> {
    if until <= now() || until > now() + WAKE_MAX_S {
        bail!("put it off to a time to come, at most 30 days ahead");
    }
    let (_, had) = update_meta(id, |m| {
        if m["awaits"].is_object() {
            m["awaits"]["snooze"] = json!(until);
            true
        } else {
            false
        }
    })?;
    if !had {
        bail!("{id} waits on nothing");
    }
    append(id, "log.jsonl", &[json!({"kind": "awaits", "snooze": until, "by": by})])?;
    events::emit("hosted_awaits", json!({"actor": by, "session": id, "snooze": until}));
    Ok(())
}

/// Tell the session, starting it again if it had ended.
fn tell_reopened(id: &str, text: &str, by: &str) -> Result<()> {
    if matches!(meta(id)?["status"].as_str(), Some("stopped" | "failed")) {
        reopen(id, by, "the person did what it waited for")?;
    }
    tell(id, "message", &json!({"text": text}), "midas")
}

/// The person gives the secret it waits for: it goes where the session said,
/// and the session is told that it is set, never what it is.
pub fn give_awaited(id: &str, value: &str, by: &str) -> Result<()> {
    let m = meta(id)?;
    let a = &m["awaits"];
    let s = &a["secret"];
    let value = value.trim();
    if value.is_empty() {
        bail!("paste it first");
    }
    let said = match s["kind"].as_str() {
        Some("remote") => {
            let name = s["name"].as_str().unwrap_or("");
            let url = s["url"].as_str().map(str::to_string).or_else(|| crate::remote::url_of(name))
                .with_context(|| format!("remote {name:?} has no endpoint"))?;
            crate::remote::set(name, &url, value, by)?;
            format!("the hub now signs in to {url} as remote {name}: its tools reach you as mcp__midas__{name}__… (list midas's tools again if they are not there yet)")
        }
        Some("bot") => {
            let (target, name) = (s["target"].as_str().unwrap_or(""), s["name"].as_str().unwrap_or(""));
            crate::botsecrets::set(target, name, Some(value), by)?;
            format!("the hub keeps it as bot secret {name} for {target}")
        }
        _ => bail!("{id} waits on nothing to paste"),
    };
    let had = clear_awaits(id, "given", by)?;
    let text = format!("From midas: {by} did what you waited for ({}): {said}. You never see the value. Go on with what it was for.",
        had["text"].as_str().unwrap_or(""));
    tell_reopened(id, &text, by)
}

/// The person will not do it: the session is told to go on without.
pub fn decline_awaited(id: &str, by: &str) -> Result<()> {
    let had = clear_awaits(id, "declined", by)?;
    let text = format!("From midas: {by} will not do what you waited for ({}). Go on without it: say what that leaves undone, \
        and finish this session when nothing else is left (the finish-branch skill).", had["text"].as_str().unwrap_or(""));
    tell_reopened(id, &text, by)
}

/// This session's own wait on the person (`midas await`, the `session_await`
/// tool), through the hub: set, or done.
pub fn await_self(text: Option<&str>, steps: Option<&str>, secret: Option<&str>, url: Option<&str>, done: bool) -> Result<String> {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_default();
    let Some(id) = owner.strip_prefix("session-").filter(|i| id_ok(i)) else {
        bail!("only a session on the Midas hub page can wait on the person there; this one is {}",
              if owner.is_empty() { "not one" } else { &owner })
    };
    if done {
        crate::client::post(&format!("/v1/hosted/{id}/awaits"), &json!({"done": true}))?;
        return Ok("done: this session waits on nothing".into());
    }
    let text = text.map(str::trim).filter(|t| !t.is_empty()).context("say what you wait for, in a line")?;
    crate::client::post(&format!("/v1/hosted/{id}/awaits"), &json!({"text": text, "steps": steps, "secret": secret, "url": url}))?;
    Ok(format!("the page lists this session under Needs you, waiting for: {text}{}. End your turn; midas tells you when it is done.",
        if secret.is_some() { " (with a field to paste it in, which goes to the hub, never to you)" } else { "" }))
}

// ── Finishing ────────────────────────────────────────────────────────────────
//
// A session is finished by the person's answer, never by a button: "Land it and
// finish" lands with `land --finish`, which asks the hub to finish it once what
// it landed is live; "Drop it" finishes it at once (`midas sessions finish
// --drop`). Finished, it is ended and archived: off the list of work, found
// under Finished and by search, its branch kept, and reopened on asking.
// One with nothing to land — a question answered, a host task done, a branch
// landed without "and finish" — finishes by itself once idle a while (`DONE_IDLE_S`).

/// How long a session waits idle before midas asks it to ask the person whether to finish.
const IDLE_ASK_S: i64 = 3 * 86400;

/// How long a session with nothing to land waits idle before it finishes: long
/// enough to read its answer and follow up while its agent is still there.
const DONE_IDLE_S: i64 = 15 * 60;

/// The session this worktree is (`session-<id>`), from its owner name.
pub fn id_of_owner(owner: &str) -> Option<String> {
    owner.strip_prefix("session-").filter(|i| id_ok(i)).map(str::to_string)
}

/// Finish a session: now (`drop`, nothing landed), or once `sha` — landed in
/// project `repo`, the session's own when unsaid — is live. A session that
/// landed in several projects says each (`land --finish` in each): it finishes
/// once every one of them is live.
pub fn finish(id: &str, by: &str, sha: Option<&str>, repo: Option<&str>, drop: bool) -> Result<String> {
    meta(id)?;
    if drop {
        done(id, json!({"outcome": "dropped", "at": now(), "by": by}), by)?;
        return Ok(format!("{id} is finished: dropped, its branch kept"));
    }
    let sha = sha.filter(|s| crate::deploy::is_sha(s)).context("finishing after a landing needs the landed commit's full sha")?;
    let repo = repo.map(str::trim).filter(|r| !r.is_empty()).and_then(|r| crate::mirror::repo_name(r).ok()).map(|r| r.trim_end_matches(".git").to_string());
    update_meta(id, |m| {
        let repo = repo.clone().map(Value::from).unwrap_or_else(|| m["repo"].clone());
        // One landing per project: a project landed again replaces its sha.
        let mut landed: Vec<Value> = m["finish"]["landed"].as_array().cloned().unwrap_or_default();
        landed.retain(|l| l["repo"] != repo);
        landed.push(json!({"sha": sha, "repo": repo}));
        m["finish"] = json!({"sha": sha, "at": now(), "by": by, "landed": landed});
    })?;
    append(id, "log.jsonl", &[json!({"kind": "finishing", "sha": sha})])?;
    events::emit("hosted_finishing", json!({"actor": by, "session": id, "sha": sha}));
    Ok(format!("{id} finishes once {} is live", &sha[..8]))
}

/// Finished on the person's word from the page (Mark done): ended and filed as
/// done, whatever its branch holds, which stays.
pub fn mark_done(id: &str, by: &str) -> Result<()> {
    let m = meta(id)?;
    if m["finished"].is_object() {
        bail!("{id} is finished already");
    }
    if m["imported"].is_object() {
        bail!("{id} was imported: a record, not a session at work");
    }
    done(id, json!({"outcome": "done", "at": now(), "by": by}), by)
}

/// Ended, archived and marked finished; said in its conversation.
fn done(id: &str, finished: Value, by: &str) -> Result<()> {
    let (m, _) = update_meta(id, |m| {
        m["finished"] = finished.clone();
        m["finish"] = Value::Null;
        m["archived"] = json!(true);
        // Finished on the person's word: what it was to do later is not done,
        // and what it waited on them for is no longer wanted.
        m["wake"] = Value::Null;
        m["awaits"] = Value::Null;
    })?;
    append(id, "log.jsonl", &[json!({"kind": "finished", "outcome": finished["outcome"], "sha": finished["sha"], "live_at": finished["live_at"]})])?;
    if !matches!(m["status"].as_str(), Some("stopped" | "failed")) {
        let _ = tell(id, "stop", &json!({}), by);
    }
    if let Some(owner) = m["owner"].as_str() {
        let _ = crate::collab::set_archived(owner, true, by);
    }
    events::emit("hosted_finished", json!({"actor": by, "session": id, "outcome": finished["outcome"]}));
    Ok(())
}

/// The hub's watch: a session waiting to finish does once what it landed is
/// live — at once in a project the hub does not deploy after landings — and
/// one idle for days is told to ask the person whether to finish, once.
pub fn finish_sweep() {
    let serving = crate::ship::serving();
    backfill_active();
    for m in list().as_array().into_iter().flatten() {
        let Some(id) = m["id"].as_str() else { continue };
        // Set to carry on later: woken when it is time, and until then neither finished nor asked to be.
        if let Some(at) = m["wake"]["at"].as_i64() {
            if at <= now() {
                let _ = wake(id, "midas");
            }
            continue;
        }
        if let Some(sha) = m["finish"]["sha"].as_str() {
            // What it landed: each project's commit (before projects were said, its one).
            let landed: Vec<(String, Value)> = match m["finish"]["landed"].as_array() {
                Some(l) => l.iter().filter_map(|l| Some((l["sha"].as_str()?.to_string(), l["repo"].clone()))).collect(),
                None => vec![(sha.to_string(), m["repo"].clone())],
            };
            // Not mid-turn: the agent that landed it says so first, and is not cut off. A task it left
            // running in the background keeps it "working" after its turn; that does not hold up the
            // finish the person asked for (finishing ends the agent and its tasks): one hung for good
            // kept a landed session open for a day.
            let between_turns = matches!(m["status"].as_str(), Some("waiting" | "stopped" | "failed"))
                || (m["status"] == "working" && turn_over(id));
            let live = |sha: &str, repo: &Value| repo.as_str().is_none_or(|r| !serving.ships(r) || serving.is_live(r, sha));
            if between_turns && landed.iter().all(|(sha, repo)| live(sha, repo)) {
                let _ = done(id, json!({"outcome": "landed", "sha": sha, "at": now(), "live_at": now()}), "midas");
            }
            continue;
        }
        // Waiting on the person for something only they can do: idle on purpose, neither finished nor asked to be.
        if m["awaits"].is_object() {
            continue;
        }
        // Nothing to land: its runner's last report found the branch on main and no files changed.
        // Idle since it last did something: a runner starting again does not reset it.
        let idle_for = active_of(m).map_or(0, |u| now() - u);
        // Sessions from before `clean` was kept: a report with no files and no commits.
        let clean = m["clean"].as_bool().unwrap_or_else(|| {
            let f = read_json(&dir(id).join("files.json"));
            f["commits"] == 0 && f["files"].as_array().is_some_and(Vec::is_empty)
        });
        let nothing_to_land = m["status"] == "waiting" && clean && m["archived"] != true && m["finished"].is_null() && m["local"].is_null()
            && m["imported"].is_null() && idle_for > DONE_IDLE_S;
        if nothing_to_land {
            let _ = done(id, json!({"outcome": "done", "at": now(), "by": "midas"}), "midas");
            continue;
        }
        let idle = m["status"] == "waiting" && m["archived"] != true && m["finished"].is_null() && m["local"].is_null()
            && m["asked_finish"].is_null() && idle_for > IDLE_ASK_S;
        if idle {
            let text = "From midas: this session has been idle for three days. Ask the person, with AskUserQuestion, \
                whether to finish it: Land it and finish (when its branch has work to land), Drop it, or Keep it open — \
                the finish-branch skill says how each is done.";
            if tell(id, "message", &json!({"text": text}), "midas").is_ok() {
                let _ = update_meta(id, |m| m["asked_finish"] = json!(now()));
            }
        }
    }
}

/// Whether its last turn has ended: in its log, the last turn's end comes after
/// the last thing said to it. What still runs in the background does not count.
fn turn_over(id: &str) -> bool {
    let (log, _) = lines(id, "log.jsonl", 0);
    log.iter().rev().find_map(|i| match i["kind"].as_str() {
        Some("turn_end") => Some(true),
        Some("user") => Some(false),
        _ => None,
    }) == Some(true)
}

/// `midas sessions finish`: this worktree's session, from its own agent, after
/// a landing in this checkout's project.
pub fn finish_cmd(sha: Option<&str>, drop: bool) -> Result<i32> {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_default();
    let repo = crate::cli::repo_in(Path::new("."));
    let v = crate::client::post("/v1/hosted/finish", &json!({"owner": owner, "sha": sha, "repo": repo, "drop": drop}))?;
    println!("{}", v["said"].as_str().unwrap_or("finishing"));
    Ok(0)
}

// ── What its branch changes ──────────────────────────────────────────────────

/// The most a files report carries: files, and lines of diff over all of them.
const FILES_MAX: usize = 300;
pub const FILES_BODY: usize = 1024 * 1024;

/// What the session's branch changes, as its runner last reported it after a
/// turn (`report_session`): each file, added, removed or changed, with its lines
/// in and out and a piece of its diff. A report from a branch already on main
/// (nothing ahead of it any more) keeps the one before, so a landed session
/// still shows what it landed.
pub fn put_files(id: &str, report: &Value) -> Result<()> {
    meta(id)?;
    let files = report["files"].as_array().map(Vec::len).unwrap_or(0);
    if files > FILES_MAX {
        bail!("at most {FILES_MAX} files in a report");
    }
    // Whether it has anything left to land, for `finish_sweep`: kept even when the report is not.
    update_meta(id, |m| m["clean"] = json!(report["clean"] == true))?;
    if report["clean"] == true && dir(id).join("files.json").exists() {
        return Ok(());
    }
    let mut r = report.clone();
    r["at"] = json!(now());
    store::write_json(&dir(id).join("files.json"), &r, store::PUBLIC)
}

pub fn files(id: &str) -> Result<Value> {
    meta(id)?;
    let r = read_json(&dir(id).join("files.json"));
    Ok(if r.is_object() { r } else { json!({"files": [], "commits": 0}) })
}

/// Its last change as `secs` ago, for tests of what idles.
#[cfg(test)]
pub fn backdate(id: &str, secs: i64) {
    update_meta(id, |m| {
        m["updated"] = json!(now() - secs);
        m["active"] = json!(now() - secs);
    }).unwrap();
}

/// The time it was set to carry on has come, for tests.
#[cfg(test)]
pub fn wake_due(id: &str) {
    update_meta(id, |m| m["wake"]["at"] = json!(now() - 1)).unwrap();
}

/// What was said to a session, for tests.
#[cfg(test)]
pub fn inbox(id: &str) -> Vec<Value> {
    lines(id, "inbox.jsonl", 0).0
}

/// A session a person archives on the page is done: one that lives in an
/// editor now (mirrored, not ended, not handed over) is ended there too, as
/// Continue on midas closes it (tap.rs). Its editor's own archive is the
/// editor's: the thread stays in its list.
pub fn archived_by_person(id: &str, by: &str) -> Result<()> {
    let m = meta(id)?;
    let live = m["local"].is_object() && !m["handed"].is_object() && !matches!(m["status"].as_str(), Some("stopped" | "failed"));
    if live { tell(id, "done", &json!({}), by) } else { Ok(()) }
}

/// Gone: an ended session's record, here. Its runner removes its worktree
/// (`poll` says which); its branch stays in the repository, with its work.
pub fn delete(id: &str, by: &str) -> Result<()> {
    let m = meta(id)?;
    if !matches!(m["status"].as_str(), Some("stopped" | "failed")) {
        bail!("{id} is still running: stop it first");
    }
    let _l = lock()?;
    fs::remove_dir_all(dir(id))?;
    let mut gone = read_json(&root().join("deleted.json")).as_array().cloned().unwrap_or_default();
    gone.retain(|g| now() - g["at"].as_i64().unwrap_or(0) < 7 * 86400);
    gone.push(json!({"id": id, "owner": m["owner"], "branch": m["branch"], "at": now(), "by": by}));
    store::write_json(&root().join("deleted.json"), &gone, store::PUBLIC)?;
    events::emit("hosted_deleted", json!({"actor": by, "session": id, "branch": m["branch"]}));
    Ok(())
}

/// Sessions deleted in the last week, for runners to clear their worktrees.
fn deleted() -> Vec<Value> {
    read_json(&root().join("deleted.json")).as_array().cloned().unwrap_or_default()
}

/// A runner asks for work: sessions to start (they are its now), and what was
/// said to its sessions since the inbox lines it has. Waits up to `POLL_S`
/// for either. A mirror (`take` false) asks only for what was said: it starts nothing.
pub fn poll(runner: &str, have: &Value, take: bool) -> Result<Value> {
    poll_with(runner, have, take, &[])
}

/// As `poll`, by a runner that says what work it can do beyond sessions
/// (`can`): a round of the research tree goes only to one that says
/// `scout`, as a runner built before it would take the round and drop it.
pub fn poll_with(runner: &str, have: &Value, take: bool, can: &[&str]) -> Result<Value> {
    if !take {
        heard(runner, have)?;
    }
    let until = Instant::now() + Duration::from_secs(POLL_S);
    loop {
        // Taken before looking, so what arrives while it looks still wakes the wait below.
        let gen = *ARRIVALS.0.lock().unwrap_or_else(|p| p.into_inner());
        let mut start = Vec::new();
        // Looked at without the lock first: a pass nearly always finds nothing to start, and
        // holding the lock across every session's meta kept the page's messages waiting.
        let mine = |m: &Value| {
            m["status"] == "queued"
                || (m["status"] == "starting" && m["runner"] == runner && m["updated"].as_i64().unwrap_or(0) + POLL_S as i64 <= now()
                    && have.get(m["id"].as_str().unwrap_or("")).is_none())
        };
        if take && list().as_array().into_iter().flatten().any(mine) {
            let _l = lock()?;
            let all = list();
            for m in all.as_array().into_iter().flatten().filter(|m| m["status"] == "queued") {
                let id = m["id"].as_str().unwrap_or("").to_string();
                let mut m = m.clone();
                m["status"] = json!("starting");
                m["runner"] = json!(runner);
                m["updated"] = json!(now());
                write_meta(&id, &m)?;
                start.push(m);
            }
            // Given to this runner and never started: the poll that took it was one a runner
            // left (a restart) and its answer went nowhere. It is given again, once a poll's time
            // has passed, so that a session whose start keeps failing is not started without end.
            for m in all.as_array().into_iter().flatten().filter(|m| m["status"] == "starting" && m["runner"] == runner) {
                let id = m["id"].as_str().unwrap_or("").to_string();
                let stale = m["updated"].as_i64().unwrap_or(0) + POLL_S as i64 <= now();
                if !stale || have.get(&id).is_some() {
                    continue;
                }
                let mut m = m.clone();
                m["updated"] = json!(now());
                write_meta(&id, &m)?;
                start.push(m);
            }
        }
        let mut inputs = serde_json::Map::new();
        for (id, after) in have.as_object().into_iter().flatten() {
            let (items, _) = lines(id, "inbox.jsonl", after.as_u64().unwrap_or(0));
            if id_ok(id) && !items.is_empty() {
                inputs.insert(id.clone(), json!(items));
            }
        }
        // Bots the page asked to start or stop (botconfig.rs): a runner hosts
        // their agents, so a runner starts them.
        let bots = if take { crate::botconfig::take_requests() } else { Vec::new() };
        // Questions about the code from a voice call (ask.rs): a runner has the checkouts.
        let asks = if take { crate::ask::take() } else { Vec::new() };
        // Template runs to review (templates.rs): a runner has Claude Code.
        let reviews = if take { crate::templates::reviews_take() } else { Vec::new() };
        // The research tree's scout rounds (tree.rs): a runner has the checkouts and Claude Code.
        let scouts = if take && can.contains(&"scout") { crate::tree::rounds_take() } else { Vec::new() };
        if !start.is_empty() || !inputs.is_empty() || !bots.is_empty() || !asks.is_empty() || !reviews.is_empty() || !scouts.is_empty() || Instant::now() >= until {
            let gone: Vec<Value> = deleted().iter().map(|g| g["id"].clone()).collect();
            // Projects renamed (hosted.rs): the runner moves its checkouts of them (`follow_renames`).
            let renamed: Vec<Value> = crate::hosted::renames().into_iter()
                .map(|(from, to)| json!({"from": from, "git": crate::hosted::url(&to), "to": to})).collect();
            return Ok(json!({"start": start, "inputs": inputs, "deleted": gone, "bots": bots, "asks": asks, "reviews": reviews, "scouts": scouts,
                             "renamed": renamed}));
        }
        // Until something arrives (a message, a start, a session queued again, a bot asked for),
        // or a few seconds for what does not say so: a start given before and never taken up.
        // It was 400 ms, a listing of every session's meta several times a second per runner.
        let seen = ARRIVALS.0.lock().unwrap_or_else(|p| p.into_inner());
        let wait = Duration::from_millis(POLL_IDLE_MS).min(until.saturating_duration_since(Instant::now()));
        let _ = ARRIVALS.1.wait_timeout_while(seen, wait, |g| *g == gen);
    }
}

// ── An editor's sessions: whether its mirror still has them ─────────────────
//
// A mirror that ends cleanly says its sessions ended (tap.rs, `end_all`). One
// that does not — the workstation sleeps, the editor is killed, an update
// replaces it — says nothing, and its sessions went on reading "your turn" on
// the page, taking messages nobody would read (s413, 2026-10-23). Its long
// poll names every session it has open, so a session it stops naming is one
// it no longer has.

/// How long a mirror may go without asking after a session before the page
/// reads it as closed in the editor: a few of its polls.
const MIRROR_GONE_S: u64 = 3 * POLL_S + 30;

/// When each editor's session was last named in its mirror's poll, and when
/// this hub began listening (a restarted hub has heard nobody yet).
fn mirror_heard() -> &'static Mutex<(Instant, BTreeMap<String, Instant>)> {
    static HEARD: OnceLock<Mutex<(Instant, BTreeMap<String, Instant>)>> = OnceLock::new();
    HEARD.get_or_init(|| Mutex::new((Instant::now(), BTreeMap::new())))
}

/// A mirror asked after these sessions: heard now, and one the page had read
/// as gone is open again — in this editor, if it is still the one that has it.
fn heard(runner: &str, have: &Value) -> Result<()> {
    let ids: Vec<&String> = have.as_object().into_iter().flatten().map(|(id, _)| id).filter(|id| id_ok(id)).collect();
    {
        let mut h = mirror_heard().lock().unwrap_or_else(|p| p.into_inner());
        for id in &ids {
            h.1.insert(id.to_string(), Instant::now());
        }
    }
    for id in ids {
        let Ok(m) = meta(id) else { continue };
        if m["gone"].is_null() || m["runner"] != runner || !m["local"].is_object() {
            continue;
        }
        let (m, ()) = update_meta(id, |m| {
            m["gone"] = Value::Null;
            m["status"] = json!("waiting");
            m["updated"] = json!(now());
        })?;
        append(id, "log.jsonl", &[json!({"kind": "status", "text": format!("open in {} on {} again",
            m["local"]["client"].as_str().unwrap_or("the editor"), m["local"]["machine"].as_str().unwrap_or("?"))})])?;
        events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "waiting"}));
    }
    Ok(())
}

/// Every editor's session whose mirror stopped asking after it reads as closed
/// there: ended on the page, which says to open it in the editor again, and
/// off the board. The hub's watcher calls it.
pub fn sweep_mirrors() {
    sweep_mirrors_after(Duration::from_secs(MIRROR_GONE_S));
}

pub(crate) fn sweep_mirrors_after(gone_after: Duration) {
    let (since, heard) = {
        let h = mirror_heard().lock().unwrap_or_else(|p| p.into_inner());
        (h.0, h.1.clone())
    };
    if since.elapsed() < gone_after {
        return;
    }
    for m in list().as_array().into_iter().flatten() {
        let live = matches!(m["status"].as_str(), Some("starting" | "working" | "waiting" | "needs_permission"));
        let Some(id) = m["id"].as_str().filter(|_| live && m["local"].is_object()) else { continue };
        if heard.get(id).is_some_and(|at| at.elapsed() < gone_after) {
            continue;
        }
        let _ = mirror_gone(id);
    }
}

fn mirror_gone(id: &str) -> Result<()> {
    let (m, live) = update_meta(id, |m| {
        let live = matches!(m["status"].as_str(), Some("starting" | "working" | "waiting" | "needs_permission")) && m["local"].is_object();
        if live {
            m["gone"] = json!(now());
            m["status"] = json!("stopped");
            m["updated"] = json!(now());
        }
        live
    })?;
    if !live {
        return Ok(());
    }
    append(id, "log.jsonl", &[json!({"kind": "status", "text": format!("{} on {} no longer has it open: open the thread there again to go on",
        m["local"]["client"].as_str().unwrap_or("the editor"), m["local"]["machine"].as_str().unwrap_or("?"))})])?;
    events::emit("hosted_status", json!({"actor": m["owner"], "session": id, "status": "stopped", "gone": true}));
    events::emit("session_end", json!({"actor": m["owner"], "reason": "editor gone"}));
    Ok(())
}

// ── Imported: conversations Claude Code had elsewhere ───────────────────────
//
// `midas sessions import` reads Claude Code's transcripts where they are (a
// workstation, the agent container) and sends each here as an ended session:
// its conversation to read and search, never to reopen — the agent's own
// record of it stays on that machine. `imported.key` is Claude Code's id for
// it, so an import run again brings only what is new or has grown.

/// The largest request an import sends: a part of one conversation's log.
pub const IMPORT_BODY: usize = 4 << 20;

/// Begin (or begin again) an imported conversation: `{key, from, cwd, title,
/// prompt, branch, owner, created, updated}`. Its id, and `have` when it is
/// here already as it is (or is a session midas ran) and needs nothing sent.
pub fn import_begin(by: &str, f: &Value) -> Result<Value> {
    let key = f["key"].as_str()
        .filter(|k| !k.is_empty() && k.len() <= 64 && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
        .context("which conversation (key)?")?;
    let text = |k: &str, max: usize| -> String { f[k].as_str().unwrap_or("").chars().take(max).collect() };
    let (created, updated) = (f["created"].as_i64().unwrap_or_else(now), f["updated"].as_i64().unwrap_or_else(now));
    let title = Some(text("title", 80)).filter(|t| !t.trim().is_empty()).unwrap_or_else(|| "A conversation".into());
    // Its project, when the checkout it was had in says (`origin`'s owner/name)
    // and it is one of the workspace's: a scratch checkout's origin is no project.
    let names = project_names();
    let repo = f["repo"].as_str().and_then(|r| crate::mirror::repo_name(r).ok()).map(|r| r.trim_end_matches(".git").to_string())
        .filter(|r| names.is_empty() || names.contains(r));
    let _l = lock()?;
    let mut have = None;
    for m in list().as_array().into_iter().flatten() {
        if m["agent_session"] == key {
            return Ok(json!({"id": m["id"], "have": "a session midas ran"}));
        }
        if m["imported"]["key"] == key {
            have = Some(m.clone());
        }
    }
    let (id, mut m) = match have {
        Some(m) => {
            // Whole, and the transcript has not grown since: nothing to send.
            if m["imported"]["complete"] == true && m["updated"].as_i64() >= Some(updated) && f["replace"] != true {
                // One imported before its project was sent: given it now.
                if let Some(r) = repo.as_ref().filter(|_| m["repo"].is_null()) {
                    let mut m = m.clone();
                    m["repo"] = json!(r);
                    write_meta(m["id"].as_str().unwrap_or(""), &m)?;
                }
                return Ok(json!({"id": m["id"], "have": "imported"}));
            }
            // Cut short, or grown: its log again from the start.
            let id = m["id"].as_str().unwrap_or("").to_string();
            let _ = fs::remove_file(dir(&id).join("log.jsonl"));
            (id, m)
        }
        None => {
            let id = next_id()?;
            fs::create_dir_all(dir(&id))?;
            (id.clone(), json!({"id": id, "status": "stopped", "base": ""}))
        }
    };
    let from = text("from", 80);
    for (k, v) in [
        ("title", json!(title)), ("prompt", json!(text("prompt", 4096))), ("branch", json!(text("branch", 200))),
        ("owner", json!(text("owner", 120))), ("by", json!(format!("{by}, from {from}"))),
        ("created", json!(created)), ("updated", json!(updated)),
        ("imported", json!({"key": key, "from": from, "cwd": text("cwd", 400), "complete": false, "at": now()})),
    ] {
        m[k] = v;
    }
    if let Some(r) = repo {
        m["repo"] = json!(r);
    }
    write_meta(&id, &m)?;
    Ok(json!({"id": id}))
}

/// A part of an imported conversation's log, its times kept. `done` with the last.
pub fn import_items(id: &str, items: &[Value], done: bool) -> Result<u64> {
    let mut m = meta(id)?;
    if !m["imported"].is_object() {
        bail!("{id} was not imported: its log is its runner's");
    }
    let _l = lock()?;
    let path = dir(id).join("log.jsonl");
    // Counted, not read: a long conversation comes in many parts.
    let mut n = fs::read(&path).map(|b| b.iter().filter(|&&c| c == b'\n').count() as u64).unwrap_or(0);
    let mut buf = String::new();
    for it in items.iter().filter(|i| matches!(i["kind"].as_str(), Some("user" | "agent" | "tool" | "tool_update" | "plan" | "status" | "error"))) {
        n += 1;
        let mut it = it.clone();
        it["n"] = json!(n);
        if !it["at"].is_i64() {
            it["at"] = m["created"].clone();
        }
        buf.push_str(&it.to_string());
        buf.push('\n');
    }
    OpenOptions::new().create(true).append(true).open(&path)?.write_all(buf.as_bytes())?;
    if done {
        m["imported"]["complete"] = json!(true);
        write_meta(id, &m)?;
        events::emit("hosted_imported", json!({"session": id, "title": m["title"], "from": m["imported"]["from"], "items": n}));
    }
    Ok(n)
}

// ── Search: what was said in every session ──────────────────────────────────

/// Lower case, a character for a character, so a place found in the folded
/// text is the same place in the text as it was written.
fn fold(s: &str) -> String {
    s.chars().map(|c| c.to_lowercase().next().unwrap_or(c)).collect()
}

/// What search reads of a log item: what was said, a tool's title and what
/// it was for, a picture's caption. Tool output is left out: it is the noise.
fn searchable(it: &Value) -> Option<String> {
    let s = match it["kind"].as_str()? {
        "user" | "agent" => it["text"].as_str()?.to_string(),
        "tool" => {
            let t = it["title"].as_str().unwrap_or("");
            match it["input"]["description"].as_str().filter(|d| !d.is_empty()) {
                Some(d) => format!("{t} — {d}"),
                None => t.to_string(),
            }
        }
        "media" => it["caption"].as_str()?.to_string(),
        _ => return None,
    };
    Some(s)
}

/// A session's search index: a line per thing said or done (`n`, a tab, its
/// words on one line), the agent's text as one line however many chunks it
/// came in. Kept as `index.txt` beside the log, its first line the log's size
/// when it was made: a log that has grown since has it made again.
fn index(id: &str) -> Vec<(u64, String)> {
    let size = fs::metadata(dir(id).join("log.jsonl")).map(|m| m.len()).unwrap_or(0);
    let path = dir(id).join("index.txt");
    if let Ok(text) = fs::read_to_string(&path) {
        let mut it = text.lines();
        if it.next().and_then(|l| l.parse::<u64>().ok()) == Some(size) {
            return it.filter_map(|l| l.split_once('\t')).filter_map(|(n, t)| Some((n.parse().ok()?, t.to_string()))).collect();
        }
    }
    let mut out: Vec<(u64, String)> = Vec::new();
    let mut agent = false;
    for it in lines(id, "log.jsonl", 0).0 {
        let Some(text) = searchable(&it) else { continue };
        let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
        let is_agent = it["kind"] == "agent";
        match out.last_mut() {
            Some((_, t)) if agent && is_agent => {
                t.push(' ');
                t.push_str(&text);
            }
            _ => out.push((it["n"].as_u64().unwrap_or(0), text)),
        }
        agent = is_agent;
    }
    let mut file = format!("{size}\n");
    for (n, t) in &out {
        file.push_str(&format!("{n}\t{t}\n"));
    }
    let tmp = dir(id).join("index.txt.tmp");
    if fs::write(&tmp, file).is_ok() {
        let _ = fs::rename(tmp, path);
    }
    out
}

/// Around the first place `word` is in `text`, a line's worth.
fn snippet(text: &str, word: &str) -> String {
    let folded = fold(text);
    let at = folded.find(word).map_or(0, |b| folded[..b].chars().count());
    let len = text.chars().count();
    let (mut from, to) = (at.saturating_sub(60), (at + word.chars().count() + 120).min(len));
    // From a word's start, not the middle of one.
    if from > 0 {
        if let Some(space) = text.chars().skip(from).take(at - from).position(char::is_whitespace) {
            from += space + 1;
        }
    }
    let mid: String = text.chars().skip(from).take(to - from).collect();
    format!("{}{}{}", if from > 0 { "…" } else { "" }, mid, if to < len { "…" } else { "" })
}

/// The sessions whose title or conversation has every word of `q` in it (any
/// case), newest first, at most `limit`: each with how many places say any of
/// them, and the first that says all of them (its log item `n`, 0 for the
/// title) with the words around it.
pub fn search(q: &str, limit: usize) -> Value {
    let words: Vec<String> = fold(q).split_whitespace().map(str::to_string).collect();
    if words.is_empty() || q.trim().chars().count() < 2 {
        return json!({"results": [], "more": false});
    }
    let mut results = Vec::new();
    let mut more = false;
    for m in list().as_array().into_iter().flatten() {
        let Some(id) = m["id"].as_str() else { continue };
        let mut places = vec![(0, m["title"].as_str().unwrap_or("").to_string())];
        places.extend(index(id));
        let folded: Vec<String> = places.iter().map(|(_, t)| fold(t)).collect();
        if !words.iter().all(|w| folded.iter().any(|f| f.contains(w.as_str()))) {
            continue;
        }
        if results.len() >= limit {
            more = true;
            break;
        }
        let hits = folded.iter().filter(|f| words.iter().any(|w| f.contains(w.as_str()))).count();
        // In the conversation rather than the title, if it says it there.
        let best = (1..places.len()).find(|&i| words.iter().all(|w| folded[i].contains(w.as_str())))
            .or_else(|| (1..places.len()).find(|&i| folded[i].contains(words[0].as_str())))
            .unwrap_or(0);
        let word = words.iter().find(|w| folded[best].contains(w.as_str())).unwrap_or(&words[0]);
        results.push(json!({"id": id, "title": m["title"], "hits": hits, "n": places[best].0, "snippet": snippet(&places[best].1, word)}));
    }
    json!({"results": results, "more": more})
}

// ── What the conversations say, counted ─────────────────────────────────────
//
// The History page's Conversations (`GET /v1/hosted/stats`): per session, what
// its log holds counted once — kept as `tally.json` beside the log with the
// log's size, made again when the log grows, as the search index is — so a
// range of days and a project are a filter over 400 small objects, not a read
// of every log.

/// A tally's shape: a tally of another is made again.
const TALLY_V: u64 = 1;
/// A gap longer than this between two things said or done is a pause, not work.
const ACTIVE_GAP_S: i64 = 600;
/// The files a tally keeps, its most edited.
const TALLY_FILES: usize = 40;

/// The program a shell command runs: past `cd …`, `set -e`, `export`,
/// `source` and assignments, at the first of `&&`, `;`, `|` or a line.
fn command_word(c: &str) -> Option<String> {
    const WRAPPERS: [&str; 7] = ["sudo", "env", "time", "timeout", "nice", "nohup", "exec"];
    const PAST: [&str; 6] = ["!", "then", "do", "else", "if", "while"];
    const NOT_A_COMMAND: [&str; 10] = ["cd", "set", "export", "source", ".", "fi", "done", "for", "in", "true"];
    for part in c.split(['\n', ';', '|', '&', '(', ')', '{', '}']) {
        let mut wrapped = false;
        for w in part.split_whitespace() {
            if PAST.contains(&w) || w.contains('=') && !w.starts_with('-') || wrapped && (w.starts_with('-') || w.starts_with(|c: char| c.is_ascii_digit())) {
                continue;
            }
            if WRAPPERS.contains(&w) {
                wrapped = true;
                continue;
            }
            if NOT_A_COMMAND.contains(&w) {
                break;
            }
            let w = w.trim_matches(['"', '\'']);
            let w = w.rsplit('/').next().unwrap_or(w);
            if !w.starts_with(|c: char| c.is_ascii_alphabetic()) {
                break;
            }
            return Some(w.chars().take(40).collect());
        }
    }
    None
}

/// A file a session changed, as the checkout names it: past a worktree's
/// root or the conversation's directory. None for one outside any checkout
/// (Claude Code's own notes and tool results).
fn checkout_path(p: &str, cwd: &str) -> Option<String> {
    if p.contains("/.claude/projects/") {
        return None;
    }
    if let Some((_, rest)) = p.split_once("/.claude/worktrees/") {
        return rest.split_once('/').map(|(_, f)| f.to_string());
    }
    let cwd = cwd.trim_end_matches('/');
    if let Some(f) = p.strip_prefix(cwd).and_then(|f| f.strip_prefix('/')).filter(|_| !cwd.is_empty()) {
        return Some(f.to_string());
    }
    // A checkout under ~/code (the workstations'): past its name.
    if let Some((_, rest)) = p.split_once("/code/") {
        return rest.split_once('/').map(|(_, f)| f.to_string());
    }
    Some(p.to_string())
}

fn bump(map: &mut BTreeMap<String, u64>, key: impl Into<String>) {
    *map.entry(key.into()).or_insert(0) += 1;
}

/// One session's tally of its log (see above).
fn tally_of(m: &Value, items: &[Value]) -> Value {
    let cwd = m["imported"]["cwd"].as_str().unwrap_or("");
    let (mut tools, mut commands, mut cargo, mut skills, mut files) = Default::default();
    let (mut tool_calls, mut failed, mut replies, mut finished) = (0u64, 0u64, 0u64, false);
    let mut said = Vec::new();
    let mut times = Vec::new();
    let mut last_kind = "";
    for it in items {
        if let Some(t) = it["at"].as_i64() {
            times.push(t);
        }
        let kind = it["kind"].as_str().unwrap_or("");
        match kind {
            "user" => said.push(it["at"].as_i64().unwrap_or(0)),
            "agent" if last_kind != "agent" => replies += 1,
            "tool" => {
                tool_calls += 1;
                let title = it["title"].as_str().unwrap_or("");
                let name = title.split(':').next().unwrap_or("").trim();
                let name = if name.is_empty() { "?" } else { name };
                bump(&mut tools, name);
                let input = &it["input"];
                match name {
                    "Bash" => {
                        let c = input["command"].as_str().unwrap_or("");
                        if let Some(w) = command_word(c) {
                            bump(&mut commands, w);
                        }
                        for (i, _) in c.match_indices("cargo ") {
                            if let Some(sub) = c[i + 6..].split_whitespace().next().filter(|w| w.chars().all(|c| c.is_ascii_lowercase() || c == '-')) {
                                bump(&mut cargo, sub);
                            }
                        }
                    }
                    "Skill" => {
                        let skill = input["skill"].as_str().unwrap_or("?");
                        // A worktree's own copy is the skill all the same.
                        let skill = skill.rsplit(':').next().unwrap_or(skill);
                        finished |= skill == "finish-branch";
                        bump(&mut skills, skill);
                    }
                    "Edit" | "Write" | "MultiEdit" | "NotebookEdit" => {
                        if let Some(f) = input["file_path"].as_str().or(input["notebook_path"].as_str()).and_then(|p| checkout_path(p, cwd)) {
                            bump(&mut files, f);
                        }
                    }
                    _ => {}
                }
            }
            "tool_update" if it["status"] == "failed" => failed += 1,
            _ => {}
        }
        if kind != "status" && kind != "tool_update" {
            last_kind = kind;
        }
    }
    times.sort_unstable();
    let active: i64 = times.windows(2).map(|w| (w[1] - w[0]).min(ACTIVE_GAP_S)).sum();
    let mut files: Vec<(String, u64)> = BTreeMap::into_iter(files).collect();
    files.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    files.truncate(TALLY_FILES);
    let files: serde_json::Map<String, Value> = files.into_iter().map(|(f, n)| (f, json!(n))).collect();
    json!({
        "start": times.first().copied().or(m["created"].as_i64()),
        "end": times.last().copied().or(m["updated"].as_i64()),
        "active_s": active, "said": said, "replies": replies, "tool_calls": tool_calls, "failed": failed,
        "finished": finished, "tools": tools, "commands": commands, "cargo": cargo, "skills": skills, "files": files,
    })
}

/// A session's tally, from `tally.json` while its log has not grown.
fn tally(id: &str, m: &Value) -> Value {
    let size = fs::metadata(dir(id).join("log.jsonl")).map(|m| m.len()).unwrap_or(0);
    let path = dir(id).join("tally.json");
    let kept = read_json(&path);
    if kept["size"] == size && kept["v"] == TALLY_V {
        return kept["tally"].clone();
    }
    let t = tally_of(m, &lines(id, "log.jsonl", 0).0);
    let tmp = dir(id).join("tally.json.tmp");
    if fs::write(&tmp, json!({"v": TALLY_V, "size": size, "tally": t}).to_string()).is_ok() {
        let _ = fs::rename(tmp, path);
    }
    t
}

/// Every session that said or did something in the last `since` seconds,
/// each with its tally: its title, project and where it was had beside it.
pub fn stats(since: i64) -> Value {
    let from = now() - since;
    let mut out = Vec::new();
    for m in list().as_array().into_iter().flatten() {
        let Some(id) = m["id"].as_str() else { continue };
        if m["updated"].as_i64().is_some_and(|u| u < from) {
            continue;
        }
        let mut t = tally(id, m);
        if t["end"].as_i64().is_some_and(|e| e < from) || t["start"].is_null() {
            continue;
        }
        for (k, v) in [("id", json!(id)), ("title", m["title"].clone()), ("repo", m["repo"].clone()),
                       ("imported", m["imported"]["from"].clone()), ("archived", json!(m["archived"] == true))] {
            t[k] = v;
        }
        out.push(t);
    }
    json!(out)
}

// ── Media: what an agent shows the person ───────────────────────────────────

// ── Images a person pastes ────────────────────────────────────────────────────
//
// Pasted on the page, an image is uploaded at once (`upload`), to be sent with
// the message it goes with: `take_upload` moves it into that session's media,
// where the page shows it with the message, and gives it to the runner inline
// (base64) for the agent. One never sent is gone after a day.

/// The largest image a person may paste.
pub const UPLOAD_MAX: usize = 10 << 20;
/// Images with one message, at most.
pub const IMAGES_MAX: usize = 5;

fn uploads() -> PathBuf {
    root().join("_uploads")
}

/// Keep a pasted image until its message is sent. Returns its token.
pub fn upload(name: &str, bytes: &[u8]) -> Result<String> {
    if bytes.len() > UPLOAD_MAX {
        bail!("{} MB is more than one image may be ({} MB)", bytes.len() >> 20, UPLOAD_MAX >> 20);
    }
    let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).take(60).collect();
    let safe = safe.trim_start_matches('.');
    // The agent takes these four; a name without one of their ends is not an image to it.
    if !matches!(mime_of(safe), "image/png" | "image/jpeg" | "image/gif" | "image/webp") {
        bail!("an image is a .png, .jpg, .gif or .webp");
    }
    let d = uploads();
    fs::create_dir_all(&d)?;
    // Uploads never sent, from more than a day ago, go.
    for e in fs::read_dir(&d)?.flatten() {
        if e.metadata().and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|a| a > Duration::from_secs(86400))) {
            let _ = fs::remove_file(e.path());
        }
    }
    let token = format!("u-{}-{safe}", crate::mirror::random_hex(8)?);
    fs::write(d.join(&token), bytes)?;
    Ok(token)
}

/// A pasted image, into session `id`'s media and out as the message carries
/// it: its file there, its type, and its bytes (base64) for the runner.
fn take_upload(id: &str, token: &str) -> Result<Value> {
    if !token.starts_with("u-") || !file_ok(token) {
        bail!("not a pasted image: {token}");
    }
    let from = uploads().join(token);
    let bytes = fs::read(&from).with_context(|| format!("no pasted image {token} (more than a day old?)"))?;
    let name = token.splitn(3, '-').nth(2).unwrap_or("image.png");
    let d = dir(id).join("media");
    fs::create_dir_all(&d)?;
    let n = fs::read_dir(&d)?.count() + 1;
    let file: String = format!("{n}-{name}").chars().take(120).collect();
    fs::write(d.join(&file), &bytes)?;
    let _ = fs::remove_file(&from);
    Ok(json!({"file": file, "mime": mime_of(&file), "data": data_encoding::BASE64.encode(&bytes)}))
}

/// The images a message names (upload tokens), taken into the session.
fn take_uploads(id: &str, images: &Value) -> Result<Vec<Value>> {
    let tokens: Vec<&str> = images.as_array().into_iter().flatten().filter_map(Value::as_str).collect();
    if tokens.len() > IMAGES_MAX {
        bail!("at most {IMAGES_MAX} images with one message");
    }
    tokens.iter().map(|t| take_upload(id, t)).collect()
}

/// Files with one message that are not pictures (a device's log, a recording):
/// `{name, data}` (base64) in, kept in the session's media, and out as the
/// message carries them, for the runner to put where its agent can read them.
fn take_files(id: &str, files: &Value) -> Result<Vec<Value>> {
    let all = files.as_array().cloned().unwrap_or_default();
    if all.len() > IMAGES_MAX {
        bail!("at most {IMAGES_MAX} files with one message");
    }
    all.iter().map(|f| {
        let name = f["name"].as_str().unwrap_or("file");
        let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).take(60).collect();
        let safe = safe.trim_start_matches('.');
        let data = f["data"].as_str().unwrap_or("");
        let bytes = data_encoding::BASE64.decode(data.as_bytes()).context("a file's data is base64")?;
        if bytes.len() > UPLOAD_MAX {
            bail!("{name} is more than {} MB", UPLOAD_MAX >> 20);
        }
        let d = dir(id).join("media");
        fs::create_dir_all(&d)?;
        let n = fs::read_dir(&d)?.count() + 1;
        let file: String = format!("{n}-{}", if safe.is_empty() { "file" } else { safe }).chars().take(120).collect();
        fs::write(d.join(&file), &bytes)?;
        Ok(json!({"file": file, "mime": mime_of(&file), "data": data}))
    }).collect()
}

/// The largest file a session may show: a short film, not a disk image.
pub const MEDIA_MAX: usize = 100 << 20;

/// What a file is, from its name: what the page can show in place.
pub fn mime_of(name: &str) -> &'static str {
    let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
    match ext.as_str() {
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "avif" => "image/avif",
        "svg" => "image/svg+xml",
        "mp3" => "audio/mpeg",
        "wav" => "audio/wav",
        "ogg" | "oga" | "opus" => "audio/ogg",
        "flac" => "audio/flac",
        "m4a" => "audio/mp4",
        "mp4" | "m4v" => "video/mp4",
        "webm" => "video/webm",
        "mov" => "video/quicktime",
        "txt" | "log" | "md" => "text/plain; charset=utf-8",
        "pdf" => "application/pdf",
        _ => "application/octet-stream",
    }
}

/// A file name as the hub keeps it: letters, digits, `.-_`, nothing that walks.
pub(crate) fn file_ok(name: &str) -> bool {
    !name.is_empty() && name.len() <= 120 && !name.starts_with('.')
        && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}

/// A line in a session's conversation the hub writes itself: a call to a device (device.rs).
pub fn status_line(id: &str, text: &str) -> Result<()> {
    if !id_ok(id) || !dir(id).is_dir() {
        bail!("no session {id}");
    }
    append(id, "log.jsonl", &[json!({"kind": "status", "text": text})])?;
    Ok(())
}

/// Keep a file a session shows, and put it in its log for the page. Returns its name.
pub fn add_media(id: &str, name: &str, caption: Option<&str>, bytes: &[u8]) -> Result<String> {
    meta(id)?;
    if bytes.len() > MEDIA_MAX {
        bail!("{} MB is more than a session may show ({} MB)", bytes.len() >> 20, MEDIA_MAX >> 20);
    }
    let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).collect();
    let safe = safe.trim_start_matches('.');
    let d = dir(id).join("media");
    fs::create_dir_all(&d)?;
    let n = fs::read_dir(&d)?.count() + 1;
    let file = format!("{n}-{}", if safe.is_empty() { "file" } else { safe });
    let file: String = file.chars().take(120).collect();
    fs::write(d.join(&file), bytes)?;
    let caption = caption.map(str::trim).filter(|c| !c.is_empty());
    append(id, "log.jsonl", &[json!({"kind": "media", "file": file, "mime": mime_of(&file), "caption": caption})])?;
    events::emit("hosted_media", json!({"session": id, "file": file, "bytes": bytes.len()}));
    Ok(file)
}

/// Where a shown file is, if it is one.
pub fn media_path(id: &str, file: &str) -> Option<PathBuf> {
    let p = dir(id).join("media").join(file);
    (id_ok(id) && file_ok(file) && p.is_file()).then_some(p)
}

/// `midas show <file>` and the MCP tool `show`: show a picture, a sound or a
/// film to the person following this session on the page. Only a session the
/// hub runs has a page to show it on (MIDAS_OWNER `session-<id>`, set by the runner).
/// A relative path as the agent meant it. The MCP server runs in the session's
/// folder, but the agent works in a project's worktree inside it, so
/// `docs/mockups/x.png` is found in the one project that has it.
fn resolve_in_session(path: &str) -> PathBuf {
    let p = PathBuf::from(path);
    if p.is_absolute() || p.exists() {
        return p;
    }
    let found: Vec<PathBuf> = fs::read_dir(".").into_iter().flatten().flatten()
        .map(|e| e.path().join(&p))
        .filter(|c| c.is_file())
        .collect();
    match found.as_slice() {
        [one] => one.clone(),
        _ => p,
    }
}

pub fn show(path: &str, caption: Option<&str>, tech: Option<&str>) -> Result<String> {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_default();
    let Some(id) = owner.strip_prefix("session-").filter(|i| id_ok(i)) else {
        bail!("only a session started from the Midas hub page can show media there; this one is {}",
              if owner.is_empty() { "not one" } else { &owner })
    };
    let p = resolve_in_session(path);
    let p = p.as_path();
    let size = fs::metadata(p).with_context(|| format!("reading {path}"))?.len() as usize;
    if size > MEDIA_MAX {
        bail!("{} MB is more than a session may show ({} MB)", size >> 20, MEDIA_MAX >> 20);
    }
    let bytes = fs::read(p).with_context(|| format!("reading {path}"))?;
    let name = p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "file".into());
    let file = crate::client::post_media(id, &name, caption, tech, &bytes)?;
    let kept = tech.map(|t| format!(", and kept on {t} as how it works now")).unwrap_or_default();
    Ok(format!("shown on the page: {file} ({}){kept}", mime_of(&file)))
}

/// What a session is doing now, in words, as its page's spinner says it: the
/// tool running (its description, else its title), else writing or thinking;
/// waiting for the person; starting. Nothing when it is not at work.
pub fn doing(items: &[Value], status: &str) -> Option<String> {
    match status {
        "queued" | "starting" => return Some("Starting".into()),
        "needs_permission" => return Some("Waiting for you".into()),
        "working" => {}
        _ => return None,
    }
    let mut running: Vec<&Value> = Vec::new();
    // What runs in the background, as last said, and whether a prompt's turn has ended since one began.
    let (mut background, mut between) = (None, false);
    for it in items {
        match it["kind"].as_str() {
            Some("tool") => running.push(it),
            Some("tool_update") if matches!(it["status"].as_str(), Some("completed" | "failed")) => running.retain(|t| t["id"] != it["id"]),
            Some("turn_end") => {
                running.clear();
                between = true;
            }
            Some("user") => between = false,
            Some("background") => background = Some(it),
            _ => {}
        }
    }
    if let Some(t) = running.last() {
        let said = t["input"]["description"].as_str().filter(|d| !d.is_empty());
        return Some(said.or(t["title"].as_str()).unwrap_or("Working").to_string());
    }
    let tasks = background.and_then(|b| b["tasks"].as_array()).filter(|t| !t.is_empty());
    if let (true, Some(tasks)) = (between, tasks) {
        let first = tasks[0]["description"].as_str().and_then(|d| d.lines().next()).filter(|d| !d.is_empty()).unwrap_or("a task");
        let more = match tasks.len() { 1 => String::new(), n => format!(" and {} more", n - 1) };
        return Some(format!("In the background: {first}{more}"));
    }
    Some(if items.last().is_some_and(|i| i["kind"] == "agent") { "Writing" } else { "Thinking" }.into())
}

/// How long the builds a session runs now take as a rule (`builds::typical`),
/// in seconds, by the tool call or background task that runs each: what the
/// page's bar under its spinner fills against. A task in the background is
/// found by the tool call that started it, whose answer names its id.
pub fn expected(items: &[Value], typical: impl Fn(&str) -> Option<i64>) -> serde_json::Map<String, Value> {
    let mut commands: HashMap<String, &str> = HashMap::new();
    let mut running: Vec<String> = Vec::new();
    let mut tasks: &[Value] = &[];
    for it in items {
        match it["kind"].as_str() {
            Some("tool") => {
                let id = it["id"].as_str().unwrap_or_default().to_string();
                if let Some(c) = it["input"]["command"].as_str() {
                    commands.insert(id.clone(), c);
                }
                running.push(id);
            }
            Some("tool_update") => {
                let id = it["id"].as_str().unwrap_or_default();
                // "Command running in background with ID: b0j6fa80s. …"
                let task = it["output"].as_str().and_then(|o| o.split_once("with ID: ")).and_then(|(_, r)| r.split(|c: char| !c.is_ascii_alphanumeric()).next());
                if let (Some(task), Some(c)) = (task, commands.get(id).copied()) {
                    commands.insert(task.to_string(), c);
                }
                if matches!(it["status"].as_str(), Some("completed" | "failed")) {
                    running.retain(|t| t != id);
                }
            }
            Some("turn_end") => running.clear(),
            Some("background") => tasks = it["tasks"].as_array().map(Vec::as_slice).unwrap_or_default(),
            _ => {}
        }
    }
    let ids = running.into_iter().chain(tasks.iter().filter_map(|t| t["id"].as_str().map(String::from)));
    ids.filter_map(|id| Some((id.clone(), json!(typical(commands.get(&id)?)?)))).collect()
}

/// What a hosted session is doing now (`doing`), from its log, and how long
/// the builds it runs take as a rule (`expected`).
pub fn doing_now(id: &str, status: &str) -> (Option<String>, serde_json::Map<String, Value>) {
    // Only a working session's log says more than its status: the board asks
    // this of every session, the imported hundreds too, each time it is made.
    // Its last 64 KB say it: parsing all of each working log was most of what a
    // board cost. A tool started before them reads as thinking.
    let items = if status == "working" { last_lines(&dir(id).join("log.jsonl"), 64 << 10) } else { Vec::new() };
    (doing(&items, status), expected(&items, crate::builds::typical))
}

/// The whole lines in a file's last `bytes`.
pub fn last_lines(path: &Path, bytes: u64) -> Vec<Value> {
    let mut buf = Vec::new();
    // A byte more, to see whether the window begins at a line's start.
    let from = File::open(path).and_then(|mut f| {
        let from = f.metadata()?.len().saturating_sub(bytes + 1);
        f.seek(SeekFrom::Start(from))?;
        f.read_to_end(&mut buf)?;
        Ok(from)
    });
    let Ok(from) = from else { return Vec::new() };
    // Unless it is the file's start, the window begins in a line: from the end of that one.
    let skip = if from == 0 { 0 } else { buf.iter().position(|&b| b == b'\n').map_or(buf.len(), |i| i + 1) };
    buf[skip..].split(|&b| b == b'\n').filter_map(|l| serde_json::from_slice(l).ok()).collect()
}

/// For the stream: how big a session's log is now, to read it only once it grew.
pub fn log_size(id: &str) -> Option<u64> {
    id_ok(id).then(|| fs::metadata(dir(id).join("log.jsonl")).ok().map(|m| m.len())).flatten()
}

/// For the stream: a session's log lines after `after`, if there are any.
/// `at` is where the follower's last look ended (a byte, the lines before it),
/// `(0, 0)` at first: each look reads only what was appended since.
pub fn tail(id: &str, at: &mut (u64, u64), after: u64) -> Option<(Vec<Value>, u64)> {
    if !id_ok(id) {
        return None;
    }
    let path = dir(id).join("log.jsonl");
    // A log cleared and begun again is read from its start.
    if fs::metadata(&path).map(|m| m.len()).unwrap_or(0) < at.0 {
        *at = (0, 0);
    }
    let (items, n, end) = read_from(&path, at.0, at.1, after);
    *at = (end, n);
    (!items.is_empty()).then_some((items, n))
}

// ── The runner ───────────────────────────────────────────────────────────────

enum Ev {
    Agent(Value),
    AgentGone,
    Input(Value),
}

/// A message waiting for the agent: its inbox line (its id for edits), its
/// words, who said it.
#[derive(Clone)]
pub struct Queued {
    pub qid: u64,
    pub text: String,
    pub by: Value,
    /// Pasted images, and files that are not (a device's log): {file, mime, data (base64)}.
    pub images: Vec<Value>,
    /// A note midas sent on (`collab::page_note`): the page draws it as one.
    pub note: Value,
    /// The autopilot's reason for saying it (autopilot.rs), shown under it.
    pub why: Value,
}

impl Queued {
    /// A `message` from the inbox.
    pub fn from_inbox(i: &Value) -> Queued {
        Queued { qid: i["n"].as_u64().unwrap_or(0), text: i["text"].as_str().unwrap_or("").to_string(), by: i["by"].clone(),
                 images: i["images"].as_array().into_iter().chain(i["files"].as_array()).flatten().cloned().collect(), note: i["note"].clone(), why: i["why"].clone() }
    }

    /// As the hub keeps it in the session's meta, for the page: no image bytes.
    pub fn shown(q: &VecDeque<Queued>) -> Value {
        json!(q.iter().map(|q| json!({"qid": q.qid, "text": q.text, "by": q.by, "note": q.note, "why": q.why,
            "images": q.images.iter().map(|i| json!({"file": i["file"], "mime": i["mime"]})).collect::<Vec<_>>()})).collect::<Vec<_>>())
    }
}

/// What the person does to a message not yet taken: `remove`, `edit` (new
/// words), `move` (to a place, 0 first), `clear` (all), `now` (first, and
/// the turn running stops). One already taken is not here any more: too late.
/// `None` when nothing changed; `Some(true)` when the turn running is to stop.
pub fn queue_op(queue: &mut VecDeque<Queued>, i: &Value) -> Option<bool> {
    let at = i["qid"].as_u64().and_then(|q| queue.iter().position(|x| x.qid == q));
    match (i["op"].as_str(), at) {
        (Some("clear"), _) => queue.clear(),
        (Some("remove"), Some(k)) => {
            queue.remove(k);
        }
        (Some("edit"), Some(k)) => {
            if let Some(t) = i["text"].as_str().map(str::trim).filter(|t| !t.is_empty()) {
                queue[k].text = t.to_string();
            }
        }
        (Some("move"), Some(k)) => {
            let q = queue.remove(k).expect("found");
            let to = (i["to"].as_u64().unwrap_or(0) as usize).min(queue.len());
            queue.insert(to, q);
        }
        (Some("now"), Some(k)) => {
            let q = queue.remove(k).expect("found");
            queue.push_front(q);
            return Some(true);
        }
        _ => return None,
    }
    Some(false)
}

/// One session's agent, and how far its conversation has got.
struct Run {
    id: String,
    /// The page asked for it to go back to its editor, by whom: done once no turn runs.
    handing_back: Option<String>,
    agent: Child,
    stdin: ChildStdin,
    next_id: u64,
    session: Option<String>,
    /// The prompt being answered, by its request id.
    turn: Option<u64>,
    queue: VecDeque<Queued>,
    /// The queue changed since the hub last heard it.
    queue_dirty: bool,
    /// Permission requests waiting for the person: rpc id → options.
    pending: BTreeMap<String, Value>,
    /// Something runs for it outside a prompt's turn (`acp::BACKGROUND`): a
    /// background task, or a turn one woke.
    busy: bool,
    /// Questions waiting for the person (form elicitations): rpc id → the form.
    asking: BTreeMap<String, Value>,
    /// Text arriving in chunks, sent as one item every so often.
    text: String,
    out: Vec<Value>,
    status: Option<&'static str>,
    /// `session/set_mode`s asked, by request id → the mode.
    asked_modes: BTreeMap<u64, String>,
    /// `session/set_model`s asked, by request id.
    asked_models: BTreeMap<u64, String>,
    model: Option<String>,
    /// The mode the page was last told of.
    mode: Option<String>,
    /// Prompts wait while the mode the session started with is being set.
    hold: bool,
    /// Whether the hub has the agent's conversation id.
    told_session: bool,
    /// Its autopilot (autopilot.rs): on or off, and what it is deciding.
    pilot: crate::autopilot::Pilot,
    /// The log items of the requests and questions waiting, for the autopilot to read.
    asked_items: BTreeMap<String, Value>,
    /// Where the autopilot's decisions come back, as the inbox's do.
    tx: Sender<Ev>,
    /// The session's folder, which the autopilot reads.
    work: PathBuf,
}

impl Run {
    fn send(&mut self, v: &Value) -> Result<()> {
        writeln!(self.stdin, "{v}")?;
        self.stdin.flush()?;
        Ok(())
    }

    fn request(&mut self, method: &str, params: Value) -> Result<u64> {
        let id = self.next_id;
        self.next_id += 1;
        self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?;
        Ok(id)
    }

    fn item(&mut self, v: Value) {
        self.flush_text();
        self.out.push(v);
    }

    fn flush_text(&mut self) {
        if !self.text.is_empty() {
            let t = std::mem::take(&mut self.text);
            self.out.push(json!({"kind": "agent", "text": t}));
        }
    }

    /// Its status from what it waits on and what runs: asking the person,
    /// at work (a turn, or anything in the background), or idle.
    fn settle(&mut self) {
        self.status = Some(settled(!self.pending.is_empty() || !self.asking.is_empty(), self.turn.is_some() || self.busy));
    }

    fn report(&mut self, runner: &str) {
        self.flush_text();
        let items = std::mem::take(&mut self.out);
        let status = self.status.take();
        let queue = std::mem::take(&mut self.queue_dirty).then(|| Queued::shown(&self.queue));
        if items.is_empty() && status.is_none() && queue.is_none() {
            return;
        }
        // The agent's conversation id, once: what a reopen asks it to load.
        let agent = (!self.told_session).then(|| self.session.clone()).flatten();
        self.told_session |= agent.is_some();
        let body = json!({"items": items, "status": status, "runner": runner, "agent_session": agent, "queue": queue});
        if let Err(e) = crate::client::post(&format!("/v1/hosted/{}/push", self.id), &body) {
            eprintln!("{}: reporting to the hub: {e:#}", self.id);
        }
    }

    /// Ask the agent for another mode (`session/set_mode`); the page hears when it answers.
    fn set_mode(&mut self, mode: &str) -> Result<()> {
        let sid = self.session.clone().context("no ACP session yet")?;
        let id = self.request("session/set_mode", json!({"sessionId": sid, "modeId": mode}))?;
        self.asked_modes.insert(id, mode.to_string());
        Ok(())
    }

    /// The session is in `mode` now: one line in the log, once.
    fn set_model(&mut self, model: &str) -> Result<()> {
        let sid = self.session.clone().context("no ACP session yet")?;
        let id = self.request("session/set_model", json!({"sessionId": sid, "modelId": model}))?;
        self.asked_models.insert(id, model.to_string());
        Ok(())
    }

    fn model_is(&mut self, model: &str) {
        if self.model.as_deref() != Some(model) {
            self.model = Some(model.to_string());
            self.item(json!({"kind": "model", "current": model}));
        }
    }

    fn mode_is(&mut self, mode: &str) {
        if self.mode.as_deref() != Some(mode) {
            self.mode = Some(mode.to_string());
            self.item(json!({"kind": "mode", "current": mode}));
        }
    }

    /// The next queued prompt, when nothing holds it back.
    fn next_prompt(&mut self) {
        if !self.hold && self.turn.is_none() && self.session.is_some() {
            if let Some(q) = self.queue.pop_front() {
                self.queue_dirty = true;
                // In the conversation now that the agent has it, not before: until
                // then it could still be edited or taken back.
                let shown: Vec<Value> = q.images.iter().map(|i| json!({"file": i["file"], "mime": i["mime"]})).collect();
                let mut item = json!({"kind": "user", "text": q.text, "by": q.by, "images": shown});
                if q.note.is_object() {
                    item["note"] = q.note.clone();
                }
                if q.why.is_string() {
                    item["why"] = q.why.clone();
                }
                self.item(item);
                let _ = self.prompt_with(&q.text, &q.images);
            }
        }
    }

    /// What the person does to the queue (`queue_op`).
    fn edit_queue(&mut self, i: &Value) {
        let Some(now) = queue_op(&mut self.queue, i) else { return };
        if now && self.turn.is_some() {
            self.cancel_turn(i["by"].as_str().unwrap_or("?"));
        }
        self.queue_dirty = true;
        self.next_prompt();
    }

    /// Stop the turn: questions and permission requests it waits on are
    /// answered cancelled, and the agent told to stop. The turn then ends
    /// (`cancelled`), and the queue goes on.
    fn cancel_turn(&mut self, by: &str) {
        let Some(sid) = self.session.clone() else { return };
        self.asked_items.clear();
        for (rpc, _) in std::mem::take(&mut self.pending) {
            let id: Value = serde_json::from_str(&rpc).unwrap_or(Value::Null);
            let _ = self.send(&json!({"jsonrpc": "2.0", "id": id, "result": {"outcome": {"outcome": "cancelled"}}}));
        }
        for (rpc, _) in std::mem::take(&mut self.asking) {
            let id: Value = serde_json::from_str(&rpc).unwrap_or(Value::Null);
            let _ = self.send(&json!({"jsonrpc": "2.0", "id": id, "result": {"action": "cancel"}}));
        }
        let _ = self.send(&json!({"jsonrpc": "2.0", "method": "session/cancel", "params": {"sessionId": sid}}));
        self.item(json!({"kind": "status", "text": format!("cancelled by {by}")}));
    }

    /// A prompt of words and pictures: each image as ACP has one (base64 and its type).
    fn prompt_with(&mut self, text: &str, images: &[Value]) -> Result<()> {
        let sid = self.session.clone().context("no ACP session yet")?;
        let mut blocks: Vec<Value> = Vec::new();
        if !text.is_empty() {
            blocks.push(json!({"type": "text", "text": text}));
        }
        let picture = |i: &Value| matches!(i["mime"].as_str(), Some("image/png" | "image/jpeg" | "image/gif" | "image/webp"));
        blocks.extend(images.iter().filter(|i| picture(i)).map(|i| json!({"type": "image", "data": i["data"], "mimeType": i["mime"]})));
        // Any other file goes where the agent can read it, out of the repository, and is named in the prompt.
        let files: Vec<&Value> = images.iter().filter(|i| !picture(i)).collect();
        if !files.is_empty() {
            let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
            let d = PathBuf::from(home).join(".cache/midas/inbox").join(&self.id);
            fs::create_dir_all(&d)?;
            let mut said = Vec::new();
            for f in files {
                let name = f["file"].as_str().filter(|n| file_ok(n)).unwrap_or("file");
                let bytes = data_encoding::BASE64.decode(f["data"].as_str().unwrap_or("").as_bytes()).unwrap_or_default();
                let p = d.join(name);
                fs::write(&p, &bytes)?;
                said.push(format!("- {} ({} bytes)", p.display(), bytes.len()));
            }
            blocks.push(json!({"type": "text", "text": format!("Files with this message:\n{}", said.join("\n"))}));
        }
        self.turn = Some(self.request("session/prompt", json!({"sessionId": sid, "prompt": blocks}))?);
        self.status = Some("working");
        Ok(())
    }

    /// Whether nothing runs or waits: no turn, nothing queued, no request or question open.
    fn idle(&self) -> bool {
        self.turn.is_none() && self.queue.is_empty() && self.pending.is_empty() && self.asking.is_empty() && self.handing_back.is_none()
    }

    /// Hand `ask` to the autopilot, when it is on and not deciding it already.
    fn pilot_ask(&mut self, ask: crate::autopilot::Ask) {
        // Off, a question or request still goes to the person's rules, when they apply them everywhere
        // (focus.rs): answered only when a rule settles it, and nothing said otherwise.
        if !self.pilot.on {
            if matches!(ask, crate::autopilot::Ask::Next) || !self.pilot.deciding.insert(ask.key()) {
                return;
            }
            let tx = self.tx.clone();
            crate::autopilot::decide_by_rules(self.id.clone(), self.work.clone(), ask, move |mut v| {
                v["pilot"] = json!(true);
                let _ = tx.send(Ev::Input(v));
            });
            return;
        }
        if !self.pilot.deciding.insert(ask.key()) {
            return;
        }
        let (request, about) = match &ask {
            crate::autopilot::Ask::Permission(r, _) => (json!(r), "permission"),
            crate::autopilot::Ask::Question(r, _) => (json!(r), "question"),
            crate::autopilot::Ask::Next => (Value::Null, "next"),
        };
        self.item(json!({"kind": "autopilot_deciding", "request": request, "about": about}));
        let tx = self.tx.clone();
        crate::autopilot::decide(self.id.clone(), self.work.clone(), self.pilot.goal.clone(), self.pilot.nudges, ask, move |mut v| {
            // Its own, not the inbox's: nothing the page sends carries this mark.
            v["pilot"] = json!(true);
            let _ = tx.send(Ev::Input(v));
        });
    }

    /// Everything that waits for an answer now, to the autopilot: its requests and
    /// questions, or, with none and nothing running, what next.
    fn pilot_kick(&mut self) {
        let waiting: Vec<(String, Value)> = self.asked_items.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
        for (rpc, it) in waiting {
            if self.pending.contains_key(&rpc) {
                self.pilot_ask(crate::autopilot::Ask::Permission(rpc, it));
            } else if self.asking.contains_key(&rpc) {
                self.pilot_ask(crate::autopilot::Ask::Question(rpc, it));
            }
        }
        if self.idle() && !self.busy {
            self.pilot_ask(crate::autopilot::Ask::Next);
        }
    }

    /// The autopilot off, by itself, saying why.
    fn pilot_off(&mut self, why: &str) {
        self.pilot.on = false;
        self.pilot.deciding.clear();
        self.item(json!({"kind": "autopilot", "on": false, "by": crate::autopilot::BY, "why": why}));
    }

    /// What the autopilot decided that is not an answer: leave it to the person, or nothing more to do.
    /// Dropped when the session has moved past it (answered meanwhile, or a turn begun).
    fn pilot_said(&mut self, i: &Value) {
        let key = i["request"].as_str().map(str::to_string).unwrap_or_else(|| "next".into());
        self.pilot.deciding.remove(&key);
        // Only the person's rules were asked (the autopilot is off) and none settled it: it stays theirs, unsaid.
        if i["kind"] == "autopilot_pass" {
            // Turned on meanwhile: what it passed over was never put to the autopilot itself.
            if self.pilot.on {
                self.pilot_kick();
            }
            return;
        }
        let still = if key == "next" { self.idle() } else { self.pending.contains_key(&key) || self.asking.contains_key(&key) };
        if self.pilot.on && still {
            self.item(json!({"kind": i["kind"], "request": i["request"], "why": i["why"], "urgent": i["urgent"]}));
        } else {
            self.pilot_idle();
        }
    }

    /// Nothing more to decide, after a decision the session had moved past: the page stops saying it decides.
    fn pilot_idle(&mut self) {
        if self.pilot.on && self.pilot.deciding.is_empty() {
            self.item(json!({"kind": "autopilot_idle"}));
        }
    }

    /// Back to the editor it came from (`hand_back`), now that no turn runs; the
    /// session ends here either way.
    fn go_back(&mut self, m: &Value, work: &Path, runner: &str) {
        let from = &m["handed"]["from"];
        self.item(json!({"kind": "status", "text": format!("handing it back to {} on {}", from["client"].as_str().unwrap_or("the editor"),
            from["machine"].as_str().unwrap_or("?"))}));
        self.report(runner);
        self.kill();
        let agent_session = self.session.clone().or_else(|| m["agent_session"].as_str().map(str::to_string)).unwrap_or_default();
        // Handed back, the hub ends it here (`handed_back`); not, it has failed here.
        if let Err(e) = hand_back(&self.id, m, work, &agent_session) {
            self.item(json!({"kind": "error", "text": format!("could not hand it back: {e:#}; reopen it to go on here")}));
            self.status = Some("failed");
            self.report(runner);
            events::emit("session_end", json!({"actor": format!("session-{}", self.id), "reason": "hand-back failed"}));
        }
    }

    fn kill(&mut self) {
        let pg = self.agent.id() as i32;
        if pg > 1 {
            // SAFETY: kill(2) on the agent's own process group (pgid > 1, ours).
            unsafe { libc::kill(-pg, libc::SIGTERM) };
            std::thread::sleep(Duration::from_millis(500));
            unsafe { libc::kill(-pg, libc::SIGKILL) };
        }
        let _ = self.agent.wait();
        unreaped().remove(&self.agent.id());
    }
}

/// The runner's children nobody has waited for yet: each session's agent while it runs, and
/// those of the build the runner started again from. Starting again on a new build (`exec`)
/// takes no child with it, but the new image is still their parent: the idle sessions' agents
/// end when their stdin goes, and nothing waited for them — 66 zombies after ten restarts
/// (2026-10-29). So they are named to the new image, which waits for them ([`reap_orphans`]).
fn unreaped() -> std::sync::MutexGuard<'static, std::collections::BTreeSet<u32>> {
    static PIDS: Mutex<std::collections::BTreeSet<u32>> = Mutex::new(std::collections::BTreeSet::new());
    PIDS.lock().unwrap_or_else(|p| p.into_inner())
}

pub(crate) const ORPHANS_ENV: &str = "MIDAS_RUNNER_ORPHANS";

/// In a runner just started: wait for the children the image before it left (`ORPHANS_ENV`),
/// and collect any that have ended already. Before any session starts, so no child of this
/// image's own is taken from the thread that waits for it.
fn reap_orphans() {
    let named: Vec<u32> = std::env::var(ORPHANS_ENV).unwrap_or_default().split(',').filter_map(|p| p.parse().ok()).collect();
    std::env::remove_var(ORPHANS_ENV);
    // SAFETY: waitpid on any child, without blocking: only children that have ended.
    while unsafe { libc::waitpid(-1, std::ptr::null_mut(), libc::WNOHANG) } > 0 {}
    for pid in named {
        unreaped().insert(pid);
        crate::util::spawn_detached("waiting for an agent of the runner's last build", move || {
            // SAFETY: waitpid on one pid this process is the parent of.
            unsafe { libc::waitpid(pid as i32, std::ptr::null_mut(), 0) };
            unreaped().remove(&pid);
        });
    }
}

/// At most this much of a tool's input or output goes in the log: the page
/// shows it folded, and a build's whole output belongs in the branch, not here.
const TOOL_TEXT: usize = 6000;

fn clip(s: &str) -> String {
    if s.chars().count() <= TOOL_TEXT {
        return s.to_string();
    }
    let head: String = s.chars().take(TOOL_TEXT).collect();
    format!("{head}\n… ({} more characters)", s.chars().count() - TOOL_TEXT)
}

/// A session's status from whether it asks the person and whether anything
/// runs for it: a background task keeps it at work after its turn has ended,
/// so the page never calls it idle while a build it started still runs.
pub fn settled(asks: bool, runs: bool) -> &'static str {
    if asks { "needs_permission" } else if runs { "working" } else { "waiting" }
}

/// What runs for a session between its turns (`acp::BACKGROUND`), as its log
/// keeps it: the page's words for what it is doing come from the last one.
pub fn background_item(p: &Value) -> Value {
    json!({"kind": "background", "tasks": p["tasks"], "turn": p["turn"]})
}

/// Whether that says anything runs.
pub fn runs_in_background(p: &Value) -> bool {
    p["turn"] == true || p["tasks"].as_array().is_some_and(|t| !t.is_empty())
}

/// What a `session/update` notification adds to the log. A tool call carries
/// what it was given (its command, its file) and its update what came of it.
pub fn update_item(u: &Value) -> Option<Value> {
    let input = || u.get("rawInput").filter(|v| v.as_object().is_some_and(|o| !o.is_empty())).map(|v| {
        let mut v = v.clone();
        // Strings clipped where they are, so the page can still read the command.
        for (_, x) in v.as_object_mut().into_iter().flatten() {
            if let Some(s) = x.as_str().filter(|s| s.chars().count() > TOOL_TEXT) {
                *x = json!(clip(s));
            }
        }
        v
    });
    let output = || {
        let text: Vec<&str> = u["content"].as_array().into_iter().flatten().filter_map(|c| c["content"]["text"].as_str()).collect();
        (!text.is_empty()).then(|| clip(&text.join("\n")))
    };
    // A subagent's call names the call it runs under (acp.rs, `within`), for
    // the page to nest it there; null for the session's own.
    let parent = &u["_meta"]["parentToolCallId"];
    match u["sessionUpdate"].as_str()? {
        "tool_call" => Some(json!({"kind": "tool", "id": u["toolCallId"], "title": u["title"], "status": u["status"], "input": input(),
                                   "parent": parent})),
        "tool_call_update" => Some(json!({"kind": "tool_update", "id": u["toolCallId"], "title": u["title"], "status": u["status"],
                                          "output": output(), "parent": parent})),
        "plan" => Some(json!({"kind": "plan", "entries": u["entries"]})),
        // How full its context is, after a turn: tokens used of the window, and the cost so far.
        "usage_update" => Some(json!({"kind": "usage", "used": u["used"], "size": u["size"], "cost": u["cost"]["amount"]})),
        _ => None,
    }
}

/// A `session/request_permission` (its id, as text, and its params) as the log
/// has it: what it asks to do, in full — the page shows the command, not only its title.
pub fn permission_item(rpc: &str, params: &Value) -> Value {
    let call = &params["toolCall"];
    let input = update_item(&json!({"sessionUpdate": "tool_call", "rawInput": call["rawInput"]}))
        .map(|t| t["input"].clone()).unwrap_or(Value::Null);
    json!({"kind": "permission", "request": rpc, "title": call["title"], "tool": call["toolCallId"],
           "input": input, "options": params["options"]})
}

/// The answer to a question form, as ACP wants it: `accept` with only the
/// form's own fields (nothing else rides into the agent's tool input), or
/// `decline`; anything else is `cancel`.
pub fn answer_result(schema: &Value, action: &str, content: &Value) -> Value {
    match action {
        "accept" => {
            let fields = &schema["properties"];
            let kept: serde_json::Map<String, Value> = content.as_object().into_iter().flatten()
                .filter(|(k, v)| fields.get(k.as_str()).is_some() && (v.is_string() || v.as_array().is_some_and(|a| a.iter().all(Value::is_string))))
                .map(|(k, v)| (k.clone(), v.clone())).collect();
            json!({"action": "accept", "content": kept})
        }
        "decline" => json!({"action": "decline"}),
        _ => json!({"action": "cancel"}),
    }
}

/// The answer to a permission request for the option the person chose, or
/// cancelled when they chose none of those offered.
pub fn permission_outcome(options: &Value, chosen: Option<&str>) -> Value {
    let ok = chosen.is_some_and(|c| options.as_array().into_iter().flatten().any(|o| o["optionId"] == c));
    match chosen.filter(|_| ok) {
        Some(c) => json!({"outcome": {"outcome": "selected", "optionId": c}}),
        None => json!({"outcome": {"outcome": "cancelled"}}),
    }
}

/// Where the runner keeps its sessions' worktrees, and its projects' checkouts
/// (`repos/<owner>/<name>`): `MIDAS_SESSIONS_DIR`, else beside `MIDAS_SESSIONS_REPO`.
pub(crate) fn sessions_home() -> Option<PathBuf> {
    crate::client::setting("MIDAS_SESSIONS_DIR").map(PathBuf::from).or_else(|| {
        let repo = PathBuf::from(crate::client::setting("MIDAS_SESSIONS_REPO")?);
        Some(repo.parent().map(Path::to_path_buf).unwrap_or(repo))
    })
}

/// The runner's checkout of project `repo` (`owner/name`): `MIDAS_SESSIONS_REPO`
/// when that is the one (or the session names none, as before projects), else
/// one of its own, cloned the first time a session of it comes.
pub(crate) fn checkout(home: &Path, repo: Option<&str>) -> Result<PathBuf> {
    let main = crate::client::setting("MIDAS_SESSIONS_REPO").map(PathBuf::from);
    let Some(repo) = repo.filter(|r| !r.is_empty()) else {
        return main.context("the session names no project, and the runner has no MIDAS_SESSIONS_REPO");
    };
    if let Some(main) = main.filter(|d| crate::util::git(d, &["remote", "get-url", "origin"]).ok()
        .and_then(|u| crate::flush::repo_of_url(u.trim())).as_deref() == Some(repo)) {
        return Ok(main);
    }
    let dir = home.join("repos").join(crate::mirror::repo_name(repo)?.trim_end_matches(".git"));
    if !dir.join(".git").exists() {
        let all = crate::client::get("/v1/hosted/projects")?;
        let git = all.as_array().into_iter().flatten().find(|p| p["repo"] == repo).and_then(|p| p["git"].as_str())
            .with_context(|| format!("{repo} is not one of the workspace's projects"))?;
        fs::create_dir_all(dir.parent().expect("under repos"))?;
        let _ = fs::remove_dir_all(&dir);
        let out = Command::new("git").args(["clone", "-q", git]).arg(&dir).stdin(Stdio::null()).output()?;
        if !out.status.success() {
            bail!("cloning {git}: {}", String::from_utf8_lossy(&out.stderr).trim());
        }
        eprintln!("{repo}: cloned into {}", dir.display());
    }
    Ok(dir)
}

/// The command that runs a session's agent: the hub's for the one it was started with
/// (Settings ▸ Agents, `agents.rs`), else Claude Code's, which this runner's `MIDAS_AGENT` may replace.
fn agent_command(m: &Value) -> Result<String> {
    let Some(id) = m["agent"].as_str().filter(|a| *a != crate::agents::CLAUDE) else {
        return Ok(crate::client::setting("MIDAS_AGENT").unwrap_or_else(crate::acp::command));
    };
    let v = crate::client::post("/v1/hosted/runner/agent", &json!({"id": id})).with_context(|| format!("asking the hub for agent {id}"))?;
    v["command"].as_str().map(str::to_string).with_context(|| format!("the hub gave no command for agent {id}"))
}

/// The workspace's projects as the hub lists them, for a runner.
fn project_names_of_hub() -> Vec<String> {
    crate::client::get("/v1/hosted/projects").ok().and_then(|v| v.as_array().cloned()).into_iter().flatten()
        .filter_map(|p| p["repo"].as_str().map(str::to_string)).collect()
}

/// One worktree made at a time, across processes (the runner, and an agent's
/// `add_project`): two `worktree add`s at once both write the repository's
/// config, and one fails ("could not lock config file", seen starting two
/// sessions together); and a project's first clone is made once.
fn one_at_a_time(home: &Path) -> Result<File> {
    let f = OpenOptions::new().create(true).append(true).open(home.join(".worktrees.lock"))?;
    // SAFETY: flock on a descriptor we own; released when it closes.
    if unsafe { libc::flock(std::os::unix::io::AsRawFd::as_raw_fd(&f), libc::LOCK_EX) } != 0 {
        bail!("locking {}: {}", home.join(".worktrees.lock").display(), std::io::Error::last_os_error());
    }
    Ok(f)
}

/// A worktree at `work` of the checkout `repo`, on branch `session/<id>` off
/// `origin/<base>`, unless it is there already.
fn add_worktree(repo: &Path, work: &Path, id: &str, base: &str) -> Result<()> {
    let git = |args: &[&str]| -> Result<()> {
        let out = Command::new("git").arg("-C").arg(repo).args(args).stdin(Stdio::null()).output()?;
        if !out.status.success() {
            bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
        }
        Ok(())
    };
    if work.exists() {
        return Ok(());
    }
    git(&["fetch", "-q", "origin", base])?;
    let branch = format!("session/{id}");
    // Not tracking the base: the session's branch is pushed as itself. A session
    // handed over from an editor starts from its own branch, whatever was here of it.
    let new = if base == branch { "-B" } else { "-b" };
    // Its folder gone and its branch kept (removed by hand, s2 and s3 on 2026-10-23): it
    // goes on on that branch, its work and all, rather than failing to make it again.
    let _ = git(&["worktree", "prune"]);
    let kept = base != branch && git(&["rev-parse", "-q", "--verify", &format!("refs/heads/{branch}")]).is_ok();
    if kept {
        git(&["worktree", "add", "-q", &work.to_string_lossy(), &branch])
    } else {
        git(&["worktree", "add", "-q", "--no-track", new, &branch, &work.to_string_lossy(), &format!("origin/{base}")])
    }
}

/// Make the session's worktree, off `origin/<base>` in its project's checkout:
/// a session of one worktree, which is its folder (before sessions could span
/// projects, and one handed over from an editor).
fn worktree(home: &Path, m: &Value) -> Result<PathBuf> {
    let _one = one_at_a_time(home)?;
    let repo = &checkout(home, m["repo"].as_str())?;
    let id = m["id"].as_str().unwrap_or("");
    let work = home.join(format!("session-{id}"));
    add_worktree(repo, &work, id, m["base"].as_str().unwrap_or("main"))?;
    Ok(work)
}

/// What makes a folder a session's, and says which (`{"id", "base"}`): a
/// worktree in it belongs to that session (`flush::worktree_owner`), so its
/// nodes, notes and landings are the session's whichever project it is.
pub const SESSION_MARK: &str = ".midas-session";

/// The session's folder, as a session of several projects has it (`FOLDER`):
/// its agent's directory, never a repository, with a worktree per project in
/// it, each at the project's name. Made again as it was when it is gone.
fn folder(home: &Path, m: &Value) -> Result<PathBuf> {
    let id = m["id"].as_str().unwrap_or("");
    let base = m["base"].as_str().unwrap_or("main");
    let dir = home.join(format!("session-{id}"));
    // Present from the start, so Claude Code watches it for the skills each project brings (`link_skills`).
    fs::create_dir_all(dir.join(".claude/skills"))?;
    fs::write(dir.join(SESSION_MARK), json!({"id": id, "base": base}).to_string())?;
    // Its projects' hooks, which Claude Code would not load from here (hook.rs `projects`).
    store::write_json(&dir.join(".claude/settings.json"), &crate::hook::folder_settings(), store::PUBLIC)?;
    for repo in repos_of(m) {
        project_worktree(home, &dir, id, &repo, base)?;
    }
    // The memory Claude Code keeps for this directory, before the agent reads it at its start:
    // the workspace's notes, and its first project's (memory.rs `checkout`).
    if let Err(e) = crate::memory::sync(&dir, None) {
        eprintln!("{id}: its memory: {e:#}");
    }
    Ok(dir)
}

/// Project `repo`'s worktree in the session folder `dir`: at its name
/// (`owner-name` when another owner's project took that), made if it is not;
/// with the branch it leaves (`project_base`).
fn project_worktree(home: &Path, dir: &Path, id: &str, repo: &str, base: &str) -> Result<(PathBuf, String)> {
    let _one = one_at_a_time(home)?;
    let name = repo.rsplit('/').next().unwrap_or(repo);
    // One made before its project was renamed is at the old name (`follow_renames`).
    let mut work = folder_worktrees(dir).into_iter().find(|(r, _)| r == repo).map_or_else(|| dir.join(name), |(_, p)| p);
    if work.exists() && crate::cli::repo_in(&work).as_deref() != Some(repo) {
        work = dir.join(repo.replace('/', "-"));
    }
    let checkout = checkout(home, Some(repo))?;
    let mut base = project_base(repo, base);
    // Another session's branch it was started on: gone from origin once that session
    // landed (s855 on s854's, 2026-11-26), and never in a project added after, which
    // built on another project's. Then it leaves the project's main, where that work is.
    if base != format!("session/{id}") && !on_origin(&checkout, &base) {
        base = project_base(repo, "main");
    }
    add_worktree(&checkout, &work, id, &base)?;
    link_skills(dir, &work);
    Ok((work, base))
}

/// Whether `origin` of the checkout `repo` has branch `branch`.
fn on_origin(repo: &Path, branch: &str) -> bool {
    Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["ls-remote", "--exit-code", "--heads", "origin", branch])
        .stdin(Stdio::null())
        .output()
        .is_ok_and(|o| o.status.success())
}

/// The branch project `repo`'s worktree leaves and is compared with: the
/// session's `base`, unless that is the default `main` and the project lands
/// on another (hub.conf `projects.<repo>.main`, such as a deck's
/// `presentation`), which has no `main` to leave at all.
pub(crate) fn project_base(repo: &str, base: &str) -> String {
    if base != "main" || repo.is_empty() {
        return base.to_string();
    }
    crate::client::get(&format!("/v1/project?repo={repo}")).ok()
        .and_then(|p| p["main"].as_str().map(str::to_string))
        .unwrap_or_else(|| base.to_string())
}

/// A project's own skills (`.claude/skills/<name>`), where Claude Code looks
/// for them from the session's folder: linked, so they are the worktree's as
/// it changes. A name another project took first stays that project's.
fn link_skills(dir: &Path, work: &Path) {
    let Ok(skills) = fs::read_dir(work.join(".claude/skills")) else { return };
    for s in skills.flatten() {
        let to = dir.join(".claude/skills").join(s.file_name());
        if fs::symlink_metadata(&to).is_err() {
            let _ = std::os::unix::fs::symlink(s.path(), &to);
        }
    }
}

/// The projects of the session folder `dir`, in the order added.
pub fn folder_projects(dir: &Path) -> Vec<String> {
    folder_worktrees(dir).into_iter().map(|(r, _)| r).collect()
}

/// The worktrees in a session's folder: (repository, path), in the order made.
pub fn folder_worktrees(dir: &Path) -> Vec<(String, PathBuf)> {
    let mut found: Vec<(std::time::SystemTime, String, PathBuf)> = fs::read_dir(dir).into_iter().flatten().flatten()
        .map(|e| e.path()).filter(|p| p.join(".git").exists())
        .filter_map(|p| Some((fs::metadata(&p).and_then(|x| x.created().or_else(|_| x.modified())).ok()?, crate::cli::repo_in(&p)?, p)))
        .collect();
    found.sort();
    found.into_iter().map(|(_, r, p)| (r, p)).collect()
}

/// `add_project` (the MCP tool, `midas sessions add-project`): this session
/// works in project `project` too, from now on — said to the hub, which says
/// it in the conversation, and its worktree made in the session's folder.
pub fn add_project(project: &str) -> Result<String> {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_default();
    let Some(id) = id_of_owner(&owner) else {
        bail!("only a session on the Midas hub page adds projects; this one is {}", if owner.is_empty() { "not one" } else { &owner })
    };
    let home = sessions_home().context("not on the runner: no MIDAS_SESSIONS_DIR or MIDAS_SESSIONS_REPO")?;
    let dir = home.join(format!("session-{id}"));
    let mark = read_json(&dir.join(SESSION_MARK));
    if mark["id"] != id.as_str() {
        bail!("{id} works in its one worktree, {}: it began before sessions could span projects. A new session can work in several", dir.display());
    }
    let base = mark["base"].as_str().unwrap_or("main").to_string();
    let v = crate::client::post(&format!("/v1/hosted/{id}/project"), &json!({"repo": project}))?;
    let repo = v["repo"].as_str().context("the hub named no project")?.to_string();
    let (work, base) = project_worktree(&home, &dir, &id, &repo, &base)?;
    let rel = work.strip_prefix(&dir).unwrap_or(&work).display().to_string();
    let guide = ["CLAUDE.md", "AGENTS.md"].iter().find(|f| work.join(f).exists())
        .map(|f| format!(" Read ./{rel}/{f} now: it is how {repo} is built, tested and changed."))
        .unwrap_or_default();
    let mut said = format!("{repo} is in ./{rel} ({}), on branch session/{id} off origin/{base}.{guide} Run git, builds (ssh <node> …) and \
        landing (finish-branch) from inside it: the node follows the worktree a command runs in.", work.display());
    if let Some(notes) = project_memory(&dir, &repo) {
        said.push_str(&format!("\n\n{notes}"));
    }
    // What its own start hooks would have said, had the session started in it (hook.rs `start_project`).
    if let Some(start) = crate::hook::start_project(&dir, &work) {
        said.push_str(&format!("\n\nIts start hooks say:\n{start}"));
    }
    Ok(said)
}

/// The memory a project's sessions keep (memory.rs), for an agent that has
/// just added it: the session folder's own memory when it is its first project
/// (synced now, so its notes are there), else a copy of its notes in the folder
/// to read (`.midas-memory/<name>/`). Its index, and where the notes are.
fn project_memory(dir: &Path, repo: &str) -> Option<String> {
    let first = folder_projects(dir).first().is_some_and(|r| r == repo);
    let (at, index) = if first {
        crate::memory::sync(dir, None).ok()?;
        let (mem, _) = crate::memory::dir(dir).ok()?;
        let index = fs::read_to_string(mem.join("MEMORY.md")).unwrap_or_default();
        (mem, index.lines().filter(|l| !l.contains(crate::memory::WORKSPACE)).map(str::to_string).collect::<Vec<_>>())
    } else {
        let q = repo.replace('/', "%2F");
        let set = crate::client::get_auth(&format!("/v1/memory?repo={q}")).ok()?["repo"].clone();
        let at = dir.join(".midas-memory").join(repo.rsplit('/').next().unwrap_or(repo));
        fs::create_dir_all(&at).ok()?;
        let mut index = Vec::new();
        for (file, n) in set.as_object().into_iter().flatten().filter(|(f, n)| n["deleted"] != true && crate::memory::file_ok(f)) {
            fs::write(at.join(file), n["text"].as_str().unwrap_or("")).ok()?;
            index.push(n["line"].as_str().filter(|l| !l.is_empty()).map(str::to_string).unwrap_or_else(|| format!("- {file}")));
        }
        (at, index)
    };
    (!index.is_empty()).then(|| format!("What {repo}'s sessions have learnt, kept in memory ({}): read the notes that bear on the task.\n{}",
        at.display(), index.join("\n")))
}

/// A session handed over from an editor (`handed`) arrives: its worktree is
/// its branch as the editor's side pushed it, and its agent's transcript is
/// where Claude Code looks for it in this worktree, so `session/load` goes on
/// with the conversation. Only when the hub's transcript is newer than the
/// one here — a reopen after a restart keeps what the runner has done since.
fn arrive(id: &str, m: &Value, work: &Path) -> Result<()> {
    let sid = m["agent_session"].as_str().filter(|s| registry::is_uuid(s)).context("no conversation to load")?;
    let path = crate::acp::transcript(&work.to_string_lossy(), sid);
    let at = m["transcript_at"].as_i64().unwrap_or(0);
    let here = fs::metadata(&path).and_then(|x| x.modified()).ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64);
    if here.is_some_and(|h| h >= at) {
        return Ok(());
    }
    // Everything the runner had of it went with the last hand-back (`hand_back`), so nothing is lost here.
    let branch = format!("session/{id}");
    crate::util::git(work, &["fetch", "-q", "origin", &branch])?;
    crate::util::git(work, &["reset", "-q", "--hard", &format!("origin/{branch}")])?;
    crate::util::git(work, &["clean", "-fdq"])?;
    let bytes = crate::client::get_transcript(id)?;
    if let Some(d) = path.parent() {
        fs::create_dir_all(d)?;
    }
    store::write_atomic(&path, &bytes, store::PRIVATE)
}

/// Hand the session back to the editor it came from: its agent stopped (its
/// transcript whole), the worktree's work — committed or not — pushed to its
/// branch, the transcript to the hub, and the hub told (`handed_back`). The
/// editor's side brings both back when the session is opened there again.
fn hand_back(id: &str, m: &Value, work: &Path, agent_session: &str) -> Result<()> {
    let from = &m["handed"]["from"];
    let snap = crate::handoff::snapshot(work, &format!("session/{id}"), &format!("wip: {id}, handed back to {} on {}\n\n\
        What the runner's worktree had not committed when the session went back.",
        from["client"].as_str().unwrap_or("the editor"), from["machine"].as_str().unwrap_or("its machine")))?;
    let path = crate::acp::transcript(&work.to_string_lossy(), agent_session);
    let bytes = fs::read(&path).with_context(|| format!("reading its transcript, {}", path.display()))?;
    crate::client::put_transcript(id, &bytes)?;
    crate::client::post(&format!("/v1/hosted/{id}/handed_back"), &json!({"sha": snap.sha}))?;
    Ok(())
}

fn run_session(m: Value, tx: Sender<Ev>, rx: Receiver<Ev>, runner: String) {
    let id = m["id"].as_str().unwrap_or("?").to_string();
    let fail = |why: String| {
        eprintln!("{id}: {why}");
        let _ = crate::client::post(&format!("/v1/hosted/{id}/push"),
            &json!({"items": [{"kind": "error", "text": why}], "status": "failed", "runner": runner}));
    };
    // Handed over from an editor: its work and its conversation come first.
    let handed = m["handed"].is_object() && !m["local"].is_object();
    let from = m["handed"]["from"]["machine"].as_str().unwrap_or("the editor").to_string();
    // Not taken over, it goes back where it came from rather than end between the two:
    // the editor has it as it left (its transcript and its branch's tip, unchanged).
    let handed_sha = m["handed"]["sha"].clone();
    let refused = |why: String| {
        eprintln!("{id}: {why}");
        let back = crate::client::post(&format!("/v1/hosted/{id}/push"), &json!({"runner": runner,
            "items": [{"kind": "error", "text": format!("{why}; it goes back to {from}, as it left")}]}))
            .and_then(|_| crate::client::post(&format!("/v1/hosted/{id}/handed_back"), &json!({"sha": handed_sha})));
        if let Err(e) = back {
            fail(format!("{why}; and sending it back to {from}: {e:#}"));
        }
    };
    let Some(home) = sessions_home() else {
        return fail("the runner has no MIDAS_SESSIONS_DIR or MIDAS_SESSIONS_REPO (where its checkouts are)".into());
    };
    // A folder of its projects' worktrees; one handed over from an editor is its one worktree.
    let spans = in_folder(&m) && !handed;
    let work = match if spans { folder(&home, &m) } else { worktree(&home, &m) } {
        Ok(w) => w,
        Err(e) if handed => return refused(format!("making the worktree: {e:#}")),
        Err(e) => return fail(format!("making the worktree: {e:#}")),
    };
    if handed {
        if let Err(e) = arrive(&id, &m, &work) {
            return refused(format!("taking it over from {from}: {e:#}"));
        }
    }
    let agent_cmd = match agent_command(&m) {
        Ok(c) => c,
        Err(e) => return fail(format!("{e:#}")),
    };
    let mut c = Command::new("bash");
    c.arg("-c").arg(&agent_cmd).current_dir(&work)
        .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit())
        // The session's own name: its takes, notes and landing are its own.
        .env("MIDAS_OWNER", format!("session-{id}"));
    // Started again (after its runner did, or reopened), not new: the agent's session-start
    // hook marks its load as a revival, which the board does not count as a start (`hook.rs`).
    let revived = m["reopen"] == true && !handed;
    if revived {
        c.env("MIDAS_REVIVED", "1");
    }
    // SAFETY: setpgid in the child before exec, async-signal-safe.
    unsafe {
        c.pre_exec(|| {
            libc::setpgid(0, 0);
            Ok(())
        });
    }
    let mut child = match c.spawn() {
        Ok(ch) => ch,
        Err(e) => return fail(format!("starting the agent `{agent_cmd}`: {e}")),
    };
    unreaped().insert(child.id());
    let stdin = child.stdin.take().expect("piped");
    let out = child.stdout.take().expect("piped");
    let atx = tx.clone();
    std::thread::spawn(move || {
        for line in BufReader::new(out).lines().map_while(Result::ok) {
            if let Ok(v) = serde_json::from_str::<Value>(&line) {
                if atx.send(Ev::Agent(v)).is_err() {
                    return;
                }
            }
        }
        let _ = atx.send(Ev::AgentGone);
    });
    // Its name and title on the board, as a session's hooks would give them. Started again it
    // is no new start: the mark says "revive", which the board passes over (`builds::sessions_from`),
    // or every session idle for days read as begun minutes ago after each deploy (2026-10-25).
    let owner = format!("session-{id}");
    events::emit("session_start", json!({"actor": owner, "branch": m["branch"], "reason": if revived { "revive" } else { "midas" }, "repo": m["repo"]}));
    if !revived {
        events::emit("session_label", json!({"actor": owner, "branch": m["branch"], "label": m["title"]}));
    }

    let mut r = Run { id: id.clone(), agent: child, stdin, next_id: 1, session: None, turn: None, queue: VecDeque::new(), queue_dirty: false,
                      pending: BTreeMap::new(), asking: BTreeMap::new(), text: String::new(), out: Vec::new(), status: None,
                      asked_modes: BTreeMap::new(), mode: None, asked_models: BTreeMap::new(), model: None, hold: false, told_session: false, busy: false,
                      handing_back: None,
                      pilot: crate::autopilot::Pilot::of_meta(&m), asked_items: BTreeMap::new(), tx: tx.clone(), work: work.clone() };
    // Reopened, with a conversation to come back to: load it rather than start one.
    let resume = m["agent_session"].as_str().filter(|_| m["reopen"] == true).map(str::to_string);
    let mut loading = false;
    let mut open_params = Value::Null;
    let init = r.request("initialize", json!({"protocolVersion": 1,
        // Forms: the agent's questions come here as one, and the page answers them.
        "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false,
                               "elicitation": {"form": {}}}}));
    let (mut init_id, mut new_id) = (init.ok(), None);
    let mut last_report = Instant::now();
    loop {
        match rx.recv_timeout(Duration::from_millis(300)) {
            Ok(Ev::Agent(v)) => {
                let method = v["method"].as_str();
                if v.get("id").is_some() && method.is_none() {
                    // A response to us.
                    let rid = v["id"].as_u64();
                    let failed = v.get("error").filter(|e| !e.is_null());
                    if let Some(model) = rid.and_then(|n| r.asked_models.remove(&n)) {
                        match failed {
                            Some(err) => r.item(json!({"kind": "error", "text": format!("model {model}: {}",
                                err["message"].as_str().unwrap_or("the agent refused"))})),
                            None => r.model_is(&model),
                        }
                    } else if let Some(mode) = rid.and_then(|n| r.asked_modes.remove(&n)) {
                        // A mode asked for: the page's choice, or the one the session started with.
                        match failed {
                            Some(err) => r.item(json!({"kind": "error", "text": format!("mode {mode}: {}",
                                err["message"].as_str().unwrap_or("the agent refused"))})),
                            None => r.mode_is(&mode),
                        }
                        r.hold = false;
                        r.next_prompt();
                    } else if let (Some(err), true) = (failed, loading && rid == new_id) {
                        // Its conversation could not be loaded: a new one, in the same worktree.
                        loading = false;
                        r.item(json!({"kind": "status", "text": format!("its conversation could not be loaded ({}); a new one, in the same worktree and branch",
                            err["message"].as_str().unwrap_or("refused"))}));
                        new_id = r.request("session/new", open_params.clone()).ok();
                    } else if let Some(err) = failed {
                        r.item(json!({"kind": "error", "text": err["message"].as_str().unwrap_or("the agent refused")}));
                        if rid == init_id || rid == new_id {
                            r.status = Some("failed");
                            r.report(&runner);
                            r.kill();
                            return;
                        }
                        if rid == r.turn { r.turn = None; r.settle(); }
                    } else if rid == init_id {
                        init_id = None;
                        // Each paired device, as an MCP server of its own (device.rs): its tools are the session's.
                        let mut p = json!({"cwd": work, "mcpServers": crate::device::mcp_servers()});
                        // The model it was started (or last) on; midas's adapter starts Claude Code on it.
                        if let Some(model) = m["model"].as_str().filter(|x| *x != "default") {
                            p["_meta"] = json!({"claudeCode": {"options": {"model": model}}});
                        }
                        // Where it runs and how to show the person things, for an agent that takes a system prompt.
                        if v["result"]["agentCapabilities"]["sessionCapabilities"]["systemPrompt"].is_object() {
                            let mut brief = SESSION_BRIEF.to_string();
                            if spans {
                                brief.push_str(&folder_brief(&id, &work, &repos_of(&m)));
                            }
                            if handed {
                                let from = &m["handed"]["from"];
                                brief.push_str(&format!("\n\nThis conversation began in {} on {}, in {}, and was handed over to midas: you run in {} now, \
                                    a worktree of branch {}, whose last commit is what that checkout had not committed (a wip commit). Paths \
                                    earlier in the conversation are that machine's. The person can hand it back to {} from the page.",
                                    from["client"].as_str().unwrap_or("an editor"), from["machine"].as_str().unwrap_or("a workstation"),
                                    from["cwd"].as_str().unwrap_or("its checkout"), work.display(), m["branch"].as_str().unwrap_or("?"),
                                    from["client"].as_str().unwrap_or("the editor")));
                            }
                            p["systemPrompt"] = json!({"mode": "append", "content": [{"type": "text", "text": brief}]});
                        }
                        let can_load = v["result"]["agentCapabilities"]["loadSession"] == true;
                        match resume.as_deref().filter(|_| can_load) {
                            Some(sid) => {
                                let mut lp = p.clone();
                                lp["sessionId"] = json!(sid);
                                loading = true;
                                new_id = r.request("session/load", lp).ok();
                            }
                            None => new_id = r.request("session/new", p.clone()).ok(),
                        }
                        open_params = p;
                    } else if rid == new_id {
                        new_id = None;
                        r.session = if loading { resume.clone() } else { v["result"]["sessionId"].as_str().map(str::to_string) };
                        if loading {
                            r.item(json!({"kind": "status", "text": "back, with its conversation"}));
                            // What its branch changes, as after a turn: a session that had no turn since
                            // the report was kept has none, and `finish_sweep` cannot tell it has nothing to land.
                            let (id, work, base) = (id.clone(), work.clone(), m["base"].as_str().unwrap_or("main").to_string());
                            std::thread::spawn(move || {
                                // Its base as it is now: one landed while it slept is on main, not ahead of it.
                                if let Err(e) = report_session(&id, &work, &base, true) {
                                    eprintln!("{id}: reporting its files: {e:#}");
                                }
                            });
                            // What its autopilot was deciding went with the runner that stopped: not deciding any more.
                            if m["autopilot"]["state"] == "deciding" {
                                r.pilot_idle();
                            }
                            if m["cut_off"] == true {
                                r.queue.push_front(Queued { qid: 0, text: CUT_OFF.to_string(), by: json!("midas"), images: vec![], note: Value::Null, why: Value::Null });
                            }
                        }
                        r.status = Some("waiting");
                        // The modes it offers, for the page's choice; then the one it was started in.
                        // The models it offers, as the page's choice wants them (id, name), and the one it is on.
                        let models = &v["result"]["models"];
                        if let Some(current) = models["currentModelId"].as_str() {
                            let offered: Vec<Value> = models["availableModels"].as_array().into_iter().flatten()
                                .map(|x| json!({"id": x["modelId"], "name": x["name"], "description": x["description"]})).collect();
                            r.item(json!({"kind": "models", "available": offered}));
                            r.model_is(current);
                        }
                        let modes = &v["result"]["modes"];
                        if let Some(current) = modes["currentModeId"].as_str() {
                            r.item(json!({"kind": "modes", "available": modes["availableModes"]}));
                            r.mode_is(current);
                        }
                        // Only a mode it has: the page's are Claude Code's, which another agent names otherwise
                        // and would refuse, so it starts in its own.
                        let offered = |w: &str| modes["availableModes"].as_array().into_iter().flatten().any(|x| x["id"] == w);
                        let wanted = m["mode"].as_str().filter(|w| Some(*w) != r.mode.as_deref() && offered(w)).map(str::to_string);
                        if let Some(w) = wanted {
                            r.hold = r.set_mode(&w).is_ok();
                        }
                        r.next_prompt();
                    } else if rid.is_some() && rid == r.turn {
                        r.turn = None;
                        let cut = v["result"]["stopReason"] == "cancelled";
                        r.item(json!({"kind": "turn_end", "reason": v["result"]["stopReason"]}));
                        r.settle();
                        // What its branch changes now, for the page's Files: in the background, git can take a moment.
                        {
                            let (id, work, base) = (id.clone(), work.clone(), m["base"].as_str().unwrap_or("main").to_string());
                            std::thread::spawn(move || {
                                if let Err(e) = report_session(&id, &work, &base, false) {
                                    eprintln!("{id}: reporting its files: {e:#}");
                                }
                            });
                        }
                        if r.handing_back.is_some() {
                            return r.go_back(&m, &work, &runner);
                        }
                        r.next_prompt();
                        // Stopped with nothing to do next: its autopilot says what next. Not after the person
                        // stopped it, nor while a task of its own still runs (that wakes it by itself).
                        if !cut && r.idle() && !r.busy {
                            r.pilot_ask(crate::autopilot::Ask::Next);
                        }
                    }
                } else if method == Some("session/update") && r.session.is_none() {
                    // A `session/load` replaying the conversation: the log has it already.
                } else if method == Some("session/update") {
                    let u = &v["params"]["update"];
                    match u["sessionUpdate"].as_str() {
                        Some("agent_message_chunk") => {
                            if let Some(t) = u["content"]["text"].as_str() {
                                r.text.push_str(t);
                            }
                        }
                        Some("current_mode_update") => {
                            if let Some(mode) = u["currentModeId"].as_str() {
                                r.mode_is(mode);
                            }
                        }
                        _ => {
                            if let Some(it) = update_item(u) {
                                r.item(it);
                            }
                        }
                    }
                } else if method == Some(crate::acp::BACKGROUND) {
                    r.item(background_item(&v["params"]));
                    r.busy = runs_in_background(&v["params"]);
                    r.settle();
                } else if method == Some("session/request_permission") {
                    let rpc = v["id"].to_string();
                    r.pending.insert(rpc.clone(), v["params"]["options"].clone());
                    let it = permission_item(&rpc, &v["params"]);
                    r.item(it.clone());
                    r.status = Some("needs_permission");
                    r.asked_items.insert(rpc.clone(), it.clone());
                    r.pilot_ask(crate::autopilot::Ask::Permission(rpc, it));
                } else if method == Some("elicitation/create") {
                    let rpc = v["id"].to_string();
                    let p = &v["params"];
                    if p["mode"] == "form" {
                        // A question: the page shows the form and sends its answer.
                        r.asking.insert(rpc.clone(), p["requestedSchema"].clone());
                        let it = json!({"kind": "question", "request": rpc, "message": p["message"], "tool": p["toolCallId"],
                                        "schema": p["requestedSchema"]});
                        r.item(it.clone());
                        r.status = Some("needs_permission");
                        r.asked_items.insert(rpc.clone(), it.clone());
                        r.pilot_ask(crate::autopilot::Ask::Question(rpc, it));
                    } else {
                        // A link to open elsewhere (a sign-in): not something a page here can do for it.
                        let _ = r.send(&json!({"jsonrpc": "2.0", "id": v["id"], "result": {"action": "decline"}}));
                    }
                } else if v.get("id").is_some() {
                    // A request we said we cannot serve (files, terminals): refuse.
                    let _ = r.send(&json!({"jsonrpc": "2.0", "id": v["id"], "error": {"code": -32601, "message": "not offered by midas"}}));
                }
            }
            Ok(Ev::Input(i)) => match i["kind"].as_str() {
                // The autopilot's next thing to say: only while nothing else is going on, or it is stale.
                Some("message") if i["pilot"] == true => {
                    r.pilot.deciding.remove("next");
                    if r.pilot.on && r.idle() {
                        r.pilot.nudges += 1;
                        if r.pilot.nudges > crate::autopilot::MAX_NUDGES {
                            r.pilot_off(&format!("it said {} things in a row without you; over to you", crate::autopilot::MAX_NUDGES));
                        } else {
                            r.queue.push_back(Queued::from_inbox(&i));
                            r.queue_dirty = true;
                            r.next_prompt();
                        }
                    } else {
                        r.pilot_idle();
                    }
                }
                Some("message") => {
                    // The person (or midas) said something: the autopilot's run of its own begins again.
                    r.pilot.nudges = 0;
                    let q = Queued::from_inbox(&i);
                    // Now: the turn in progress stops, and this goes first when it has.
                    // Otherwise it waits its turn — in the queue, where it can still be
                    // edited, moved or taken back — and goes at once if nothing runs.
                    if r.turn.is_some() && i["now"] == true {
                        r.queue.push_front(q);
                        r.cancel_turn(i["by"].as_str().unwrap_or("?"));
                    } else {
                        r.queue.push_back(q);
                    }
                    r.queue_dirty = true;
                    r.next_prompt();
                }
                Some("model") => {
                    if let Some(model) = i["model"].as_str() {
                        if r.set_model(model).is_err() {
                            r.item(json!({"kind": "error", "text": "the session has not opened yet; choose the model again in a moment"}));
                        }
                    }
                }
                Some("mode") => {
                    if let Some(mode) = i["mode"].as_str() {
                        if r.set_mode(mode).is_err() {
                            r.item(json!({"kind": "error", "text": "the session has not opened yet; choose the mode again in a moment"}));
                        }
                    }
                }
                Some("permit") => {
                    let rpc = i["request"].as_str().unwrap_or("").to_string();
                    r.pilot.deciding.remove(&rpc);
                    r.asked_items.remove(&rpc);
                    if let Some(options) = r.pending.remove(&rpc) {
                        let outcome = permission_outcome(&options, i["option"].as_str());
                        let id: Value = serde_json::from_str(&rpc).unwrap_or(Value::Null);
                        let _ = r.send(&json!({"jsonrpc": "2.0", "id": id, "result": outcome}));
                        r.item(json!({"kind": "permission_answered", "request": rpc, "option": i["option"], "by": i["by"], "why": i["why"],
                                      "basis": i["basis"], "rule": i["rule"], "sure": i["sure"], "propose": i["propose"]}));
                        r.settle();
                    }
                }
                Some("answer") => {
                    let rpc = i["request"].as_str().unwrap_or("").to_string();
                    r.pilot.deciding.remove(&rpc);
                    r.asked_items.remove(&rpc);
                    if let Some(schema) = r.asking.remove(&rpc) {
                        let result = answer_result(&schema, i["action"].as_str().unwrap_or(""), &i["content"]);
                        let id: Value = serde_json::from_str(&rpc).unwrap_or(Value::Null);
                        let _ = r.send(&json!({"jsonrpc": "2.0", "id": id, "result": result}));
                        r.item(json!({"kind": "answered", "request": rpc, "action": result["action"], "content": result["content"], "by": i["by"], "why": i["why"],
                                      "basis": i["basis"], "rule": i["rule"], "sure": i["sure"], "propose": i["propose"]}));
                        r.settle();
                    }
                }
                // Turned on or off on the page: on, it takes up whatever waits now.
                Some("autopilot") if i["pilot"] != true => {
                    r.pilot.set(&i);
                    r.item(json!({"kind": "autopilot", "on": i["on"], "by": i["by"], "until": i["until"], "goal": i["goal"]}));
                    if r.pilot.on {
                        r.pilot_kick();
                    }
                }
                Some("autopilot_left" | "autopilot_done" | "autopilot_pass") if i["pilot"] == true => r.pilot_said(&i),
                Some("cancel") => r.cancel_turn(i["by"].as_str().unwrap_or("?")),
                Some("queue") => r.edit_queue(&i),
                Some("handback") if r.handing_back.is_none() => {
                    let by = i["by"].as_str().unwrap_or("?").to_string();
                    r.handing_back = Some(by.clone());
                    if r.turn.is_some() {
                        r.cancel_turn(&by);
                    } else {
                        return r.go_back(&m, &work, &runner);
                    }
                }
                Some("stop") => {
                    r.item(json!({"kind": "status", "text": format!("stopped by {}; the branch {} keeps its work",
                        i["by"].as_str().unwrap_or("?"), m["branch"].as_str().unwrap_or("?"))}));
                    r.status = Some("stopped");
                    r.report(&runner);
                    r.kill();
                    events::emit("session_end", json!({"actor": owner, "reason": "stopped"}));
                    return;
                }
                _ => {}
            },
            Ok(Ev::AgentGone) | Err(RecvTimeoutError::Disconnected) => {
                r.item(json!({"kind": "error", "text": "the agent ended"}));
                r.status = Some("failed");
                r.report(&runner);
                let _ = r.agent.wait();
                unreaped().remove(&r.agent.id());
                events::emit("session_end", json!({"actor": owner, "reason": "agent ended"}));
                return;
            }
            Err(RecvTimeoutError::Timeout) => {}
        }
        // The autopilot's time has run out: off, said in the conversation (and so in the meta).
        if r.pilot.expired() {
            r.pilot_off("its time ran out");
        }
        // Text as it comes, a few times a second; everything else at once.
        if !r.out.is_empty() || r.status.is_some() || r.queue_dirty || (!r.text.is_empty() && last_report.elapsed() >= Duration::from_millis(400)) {
            r.report(&runner);
            last_report = Instant::now();
        }
    }
}

/// Where a session's worktree is, as `worktree` makes it.
/// The lines of diff a report carries per file, and in all.
const PATCH_FILE: usize = 6 * 1024;
const PATCH_ALL: usize = 256 * 1024;

/// Tell the hub what the session's branch changes (`branch_changes`): in its
/// one worktree, or in each of its folder's, the paths then under the
/// project's name when there are several. Fetched first (`fetch`), its base is
/// as it is now. Nothing ahead anywhere (landed, or untouched) says `clean`,
/// and the hub keeps what it had.
fn report_session(id: &str, work: &Path, base: &str, fetch: bool) -> Result<()> {
    let trees = if work.join(".git").exists() { vec![(String::new(), work.to_path_buf())] } else { folder_worktrees(work) };
    let several = trees.len() > 1;
    let (mut files, mut commits) = (Vec::new(), 0);
    for (repo, tree) in &trees {
        let base = &project_base(repo, base);
        if fetch {
            let _ = crate::util::git(tree, &["fetch", "-q", "origin", base]);
        }
        let (f, c) = branch_changes(tree, base)?;
        let name = repo.rsplit('/').next().unwrap_or(repo);
        files.extend(f.into_iter().map(|mut f| {
            if several {
                f["path"] = json!(format!("{name}/{}", f["path"].as_str().unwrap_or("")));
            }
            f
        }));
        commits += c;
    }
    files.truncate(FILES_MAX);
    let clean = commits == 0 && files.is_empty();
    crate::client::post(&format!("/v1/hosted/{id}/files"), &json!({"files": files, "commits": commits, "base": base, "clean": clean}))?;
    Ok(())
}

/// What the branch in `work` changes against where it left its base
/// (`origin/<base>`, merge-base): committed and not, new files too, each with
/// a piece of its diff; and how many commits it is ahead.
fn branch_changes(work: &Path, base: &str) -> Result<(Vec<Value>, u64)> {
    let git = |args: &[&str]| -> Result<String> {
        let out = Command::new("git").arg("-C").arg(work).args(args).stdin(Stdio::null()).output()?;
        if !out.status.success() {
            bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
        }
        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
    };
    let mb = git(&["merge-base", "HEAD", &format!("origin/{base}")])?.trim().to_string();
    let commits: u64 = git(&["rev-list", "--count", &format!("{mb}..HEAD")])?.trim().parse().unwrap_or(0);
    let mut files: Vec<Value> = Vec::new();
    let status: BTreeMap<String, String> = git(&["diff", "--no-renames", "--name-status", &mb])?.lines()
        .filter_map(|l| l.split_once('\t')).map(|(st, f)| (f.to_string(), st.chars().next().unwrap_or('M').to_string())).collect();
    for l in git(&["diff", "--no-renames", "--numstat", &mb])?.lines() {
        let mut p = l.splitn(3, '\t');
        let (Some(a), Some(d), Some(f)) = (p.next(), p.next(), p.next()) else { continue };
        let binary = a == "-";
        files.push(json!({"path": f, "status": status.get(f).cloned().unwrap_or_else(|| "M".into()),
            "add": a.parse::<u64>().unwrap_or(0), "del": d.parse::<u64>().unwrap_or(0), "binary": binary}));
    }
    // New files not added yet are the branch's work too.
    for f in git(&["ls-files", "--others", "--exclude-standard"])?.lines().take(FILES_MAX) {
        let lines = fs::read(work.join(f)).ok().filter(|b| !b.contains(&0)).map(|b| b.iter().filter(|c| **c == b'\n').count());
        files.push(json!({"path": f, "status": "A", "add": lines.unwrap_or(0), "del": 0, "binary": lines.is_none(), "untracked": true}));
    }
    files.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str()));
    files.truncate(FILES_MAX);
    // A piece of each file's diff, the largest changes first, until the budget is spent.
    let mut order: Vec<usize> = (0..files.len()).filter(|i| files[*i]["binary"] != true && files[*i]["untracked"] != true).collect();
    order.sort_by_key(|i| std::cmp::Reverse(files[*i]["add"].as_u64().unwrap_or(0) + files[*i]["del"].as_u64().unwrap_or(0)));
    let mut spent = 0;
    for i in order {
        if spent >= PATCH_ALL {
            break;
        }
        let path = files[i]["path"].as_str().unwrap_or("").to_string();
        let Ok(d) = git(&["diff", "--no-renames", "-U2", &mb, "--", &path]) else { continue };
        // From the first hunk: the header lines say nothing the row does not.
        let body = d.find("\n@@").map(|at| &d[at + 1..]).unwrap_or("");
        let cut = crate::util::short(body, PATCH_FILE);
        spent += cut.len();
        files[i]["patch"] = json!(cut);
    }
    Ok((files, commits))
}

pub(crate) fn worktree_of(id: &str) -> Option<PathBuf> {
    Some(sessions_home()?.join(format!("session-{id}")))
}

/// `midas sessions run`: run the sessions the page starts, until stopped.
/// What a reloaded agent is told when its runner stopped in the middle of its turn.
const CUT_OFF: &str = "Your last turn was cut off: midas's sessions runner stopped while you were working, and this conversation \
    has been loaded again. Anything you had running went with it. Check what finished and what did not, then carry on \
    with what you were doing, and tell the person where things stand.";

pub fn runner() -> Result<i32> {
    if sessions_home().is_none() {
        bail!("set MIDAS_SESSIONS_DIR (hub.env or the environment) to where the runner keeps its checkouts, \
               or MIDAS_SESSIONS_REPO to a checkout of the repository sessions branch from");
    }
    let name = format!("runner@{}", std::process::Command::new("hostname").output().ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_else(|| "?".into()));
    // `midas sessions run` is the supervisor that keeps the runner proper up (runners.rs).
    if std::env::var_os(crate::runners::CHILD_ENV).is_none() {
        return crate::runners::supervise(&name);
    }
    // Before any thread: a write to an agent gone must not end the runner (it did, 2026-11-19).
    crate::runners::guard(&name);
    eprintln!("{name}: running sessions from the hub at {}", crate::client::hub_url());
    // Started again on a new build (it names the agents it left), by its supervisor, by the host's watch, or by hand.
    let by = if std::env::var_os(ORPHANS_ENV).is_some() { "build".to_string() }
        else { std::env::var(crate::runners::STARTED_BY_ENV).unwrap_or_else(|_| "hand".into()) };
    events::emit("runner_started", json!({"runner": name, "by": by, "pid": std::process::id(), "version": crate::VERSION}));
    reap_orphans();
    // A runner that starts again (a deploy, a crash) takes back the sessions it was
    // running: their agents went with it, so each is reopened and loads its conversation.
    for m in crate::client::get("/v1/hosted").ok().as_ref().and_then(Value::as_array).into_iter().flatten() {
        let live = matches!(m["status"].as_str(), Some("starting" | "working" | "waiting" | "needs_permission"));
        if let (true, true, Some(id)) = (live, m["runner"] == name.as_str(), m["id"].as_str()) {
            match crate::client::post(&format!("/v1/hosted/{id}/reopen"), &json!({"restart": true, "runner": name})) {
                Ok(_) => eprintln!("{id}: taken back after a restart"),
                Err(e) => eprintln!("{id}: could not take it back: {e:#}"),
            }
        }
    }
    let mut runs: BTreeMap<String, (Sender<Ev>, u64)> = BTreeMap::new();
    let build = Build::now();
    loop {
        // A deploy replaced the binary: start again on it once no agent is mid-turn.
        // Its agents go with it and are taken back, as after any restart.
        if build.replaced() && BOTS_BUSY.load(std::sync::atomic::Ordering::SeqCst) == 0 && !mid_turn(&name) {
            eprintln!("{name}: a new build is installed and no agent is mid-turn: starting again on it");
            // Its skills and hooks first, as deploy.sh's `claude` did: a hub's deploy of midas
            // reaches this machine only as the binary, and every session start installs them too.
            match Command::new(&build.path).args(["claude", "install"]).stdin(Stdio::null()).output() {
                Ok(o) if o.status.success() => eprintln!("{name}: the new build's skills and hooks are installed"),
                Ok(o) => eprintln!("{name}: installing the new build's skills and hooks: {}", String::from_utf8_lossy(&o.stderr).trim()),
                Err(e) => eprintln!("{name}: installing the new build's skills and hooks: {e}"),
            }
            events::emit("runner_stopped", json!({"runner": name, "reason": "build", "version": crate::VERSION, "sessions": runs.len()}));
            let orphans: Vec<String> = unreaped().iter().map(u32::to_string).collect();
            let e = Command::new(&build.path).args(std::env::args_os().skip(1)).env(ORPHANS_ENV, orphans.join(",")).exec();
            eprintln!("{name}: could not start again: {e}");
        }
        let have: serde_json::Map<String, Value> = runs.iter().map(|(id, (_, n))| (id.clone(), json!(n))).collect();
        let v = match crate::client::post("/v1/hosted/runner/poll", &json!({"runner": name, "have": have, "can": ["scout"]})) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("asking the hub: {e:#}");
                std::thread::sleep(Duration::from_secs(5));
                continue;
            }
        };
        for m in v["start"].as_array().into_iter().flatten() {
            let Some(id) = m["id"].as_str().map(str::to_string) else { continue };
            eprintln!("{id}: starting \"{}\"", m["title"].as_str().unwrap_or(""));
            let (tx, rx) = mpsc::channel();
            // A reopened session hears only what is said from now on.
            runs.insert(id.clone(), (tx.clone(), m["inbox_after"].as_u64().unwrap_or(0)));
            let (m, runner) = (m.clone(), name.clone());
            std::thread::spawn(move || run_session(m, tx, rx, runner));
        }
        for job in v["bots"].as_array().into_iter().flatten() {
            let job = job.clone();
            std::thread::spawn(move || run_bot(&job));
        }
        for job in v["asks"].as_array().into_iter().flatten() {
            let (job, path) = (job.clone(), build.path.clone());
            std::thread::spawn(move || answer_on_installed(&path, &job));
        }
        for job in v["reviews"].as_array().into_iter().flatten() {
            let job = job.clone();
            std::thread::spawn(move || crate::templates::review(&job));
        }
        for job in v["scouts"].as_array().into_iter().flatten() {
            let (job, path) = (job.clone(), build.path.clone());
            std::thread::spawn(move || scout_on_installed(&path, &job));
        }
        for (id, items) in v["inputs"].as_object().into_iter().flatten() {
            let Some((tx, n)) = runs.get_mut(id) else { continue };
            for it in items.as_array().into_iter().flatten() {
                *n = (*n).max(it["n"].as_u64().unwrap_or(0));
                let _ = tx.send(Ev::Input(it.clone()));
            }
        }
        // A session whose thread has ended hears nothing more.
        runs.retain(|_, (tx, _)| tx.send(Ev::Input(json!({"kind": "ping"}))).is_ok());
        crate::runners::SESSIONS.store(runs.len(), std::sync::atomic::Ordering::SeqCst);
        follow_renames(&sessions_home().expect("checked at the start"), &v["renamed"]);
        // Deleted on the page: its worktree goes; its branch stays, with the work.
        for id in v["deleted"].as_array().into_iter().flatten().filter_map(Value::as_str) {
            if let Some(work) = worktree_of(id).filter(|w| w.exists()) {
                // Its project's checkout, whichever that is: the repository the worktree belongs to.
                let repo = crate::util::git(&work, &["rev-parse", "--path-format=absolute", "--git-common-dir"]).ok()
                    .map(|d| PathBuf::from(d.trim())).and_then(|d| d.parent().map(Path::to_path_buf)).unwrap_or_default();
                let done = Command::new("git").arg("-C").arg(&repo).args(["worktree", "remove", "--force"]).arg(&work)
                    .stdin(Stdio::null()).status().is_ok_and(|s| s.success());
                eprintln!("{id}: deleted on the page; {}", if done { "its worktree is gone, its branch kept" } else { "could not remove its worktree" });
            }
        }
    }
}

/// The runner's checkouts of projects renamed at the hub (`renamed`: from, to,
/// git), under their new names: the checkout moved to `repos/<to>`, its
/// worktrees told where it went (`git worktree repair`), and its `origin` set
/// to the new URL, which every worktree of it shares. A session's worktree
/// keeps its folder's name (`./<old>`) under an agent that may be in it;
/// `project_worktree` finds it there by its origin. Done once: a checkout at
/// the new name already is left as it is.
pub(crate) fn follow_renames(home: &Path, renamed: &Value) {
    for r in renamed.as_array().into_iter().flatten() {
        let (Some(from), Some(to), Some(git)) = (r["from"].as_str(), r["to"].as_str(), r["git"].as_str()) else { continue };
        let (Ok(f), Ok(t)) = (crate::mirror::repo_name(from), crate::mirror::repo_name(to)) else { continue };
        let (old, new) = (home.join("repos").join(f.trim_end_matches(".git")), home.join("repos").join(t.trim_end_matches(".git")));
        if !old.join(".git").exists() || new.exists() {
            continue;
        }
        let moved = (|| -> Result<()> {
            let _one = one_at_a_time(home)?;
            fs::create_dir_all(new.parent().expect("under repos"))?;
            fs::rename(&old, &new)?;
            crate::util::git(&new, &["worktree", "repair"])?;
            crate::util::git(&new, &["remote", "set-url", "origin", git])?;
            Ok(())
        })();
        match moved {
            Ok(()) => eprintln!("{from} is {to} now: its checkout moved to {}", new.display()),
            Err(e) => eprintln!("{from} is {to} now; moving its checkout: {e:#}"),
        }
    }
}

/// The binary the runner started from, to see a deploy replace it.
pub(crate) struct Build {
    pub(crate) path: PathBuf,
    id: Option<(u64, i64)>,
}

impl Build {
    pub(crate) fn now() -> Build {
        let path = crate::util::exe().unwrap_or_default();
        Build { id: Self::id_of(&path), path }
    }

    fn id_of(path: &Path) -> Option<(u64, i64)> {
        use std::os::unix::fs::MetadataExt;
        fs::metadata(path).ok().map(|m| (m.ino(), m.mtime()))
    }

    /// Another file at its path now, one that can run.
    pub(crate) fn replaced(&self) -> bool {
        let now = Self::id_of(&self.path);
        now.is_some() && self.id.is_some() && now != self.id
    }
}

/// A round of the research tree's scout (tree.rs), run by the build installed
/// now, as questions are (`answer_on_installed`): a busy workshop keeps this
/// runner on its old build for hours, and a better scout would wait as long.
fn scout_on_installed(path: &Path, job: &Value) {
    let child = Command::new(path).args(["sessions", "scout"])
        .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::inherit()).spawn();
    match child {
        Ok(mut c) => {
            if let Some(mut i) = c.stdin.take() {
                let _ = i.write_all(job.to_string().as_bytes());
            }
            let _ = c.wait();
        }
        Err(e) => {
            eprintln!("tree round {}: the installed build would not start ({e}): running it here", job["round"].as_str().unwrap_or("?"));
            crate::tree::scout(job);
        }
    }
}

/// One code question at a time, across the processes that answer them.
static ASK_ONE: Mutex<()> = Mutex::new(());

/// A code question, answered by the build installed at `path` now rather than
/// by this runner's own: the runner starts again on a deploy only once no agent
/// is mid-turn, which a busy workshop put off for hours, and the voice's questions
/// kept failing on a fix already deployed (a deck's `presentation`, fetched as
/// `main`). In this process only when that build cannot be started.
fn answer_on_installed(path: &Path, job: &Value) {
    let _one = ASK_ONE.lock().unwrap_or_else(|p| p.into_inner());
    let child = Command::new(path).args(["sessions", "answer"])
        .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::inherit()).spawn();
    match child {
        Ok(mut c) => {
            if let Some(mut i) = c.stdin.take() {
                let _ = i.write_all(job.to_string().as_bytes());
            }
            let _ = c.wait();
        }
        Err(e) => {
            eprintln!("question {}: the installed build would not start ({e}): answering it here", job["id"].as_str().unwrap_or("?"));
            crate::ask::run(job);
        }
    }
}

/// Bots the runner is starting or stopping now, which a restart would cut off.
static BOTS_BUSY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Whether any session of this runner is in a turn, starting, or waits on the
/// person's answer, which a restart would lose; or the hub cannot say.
fn mid_turn(runner: &str) -> bool {
    let Ok(all) = crate::client::get("/v1/hosted") else { return true };
    all.as_array().into_iter().flatten().any(|m| m["runner"] == runner
        && matches!(m["status"].as_str(), Some("queued" | "starting" | "working" | "needs_permission")))
}

/// A bot the page asked to start or stop (`botconfig`). It runs from a
/// worktree of its own, `bot-<name>`, on the project's main as it is now, so
/// the bot is built from what has landed; and as that worktree, which is the
/// owner of its node and of its hosted agent.
fn run_bot(job: &Value) {
    use std::sync::atomic::Ordering::SeqCst;
    BOTS_BUSY.fetch_add(1, SeqCst);
    struct Done;
    impl Drop for Done {
        fn drop(&mut self) {
            BOTS_BUSY.fetch_sub(1, SeqCst);
        }
    }
    let _done = Done;
    let name = job["name"].as_str().unwrap_or("").to_string();
    let start = job["action"] == "start";
    let report = |state: &str, detail: &str| {
        if let Err(e) = crate::client::post("/v1/hosted/runner/bot", &json!({"name": name, "state": state, "detail": detail})) {
            eprintln!("bot {name}: could not tell the hub it is {state}: {e:#}");
        }
    };
    if !crate::host::name_ok(&name) {
        return;
    }
    let result = (|| -> Result<String> {
        let home = sessions_home().context("the runner has no sessions directory (MIDAS_SESSIONS_DIR)")?;
        let work = bot_worktree(&home, &name)?;
        let args: Vec<String> = if start {
            job["args"].as_array().context("no start command")?.iter().filter_map(|a| a.as_str().map(str::to_string)).collect()
        } else {
            vec!["bot".into(), "stop".into(), "--name".into(), name.clone()]
        };
        eprintln!("bot {name}: midas {}", args.join(" "));
        let out = Command::new(crate::util::exe()?).args(&args).current_dir(&work)
            // The bot's worktree is its owner, not whoever started the runner.
            .env_remove("MIDAS_OWNER")
            .stdin(Stdio::null()).output()?;
        let said = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
        let tail: Vec<&str> = said.lines().filter(|l| !l.trim().is_empty()).collect();
        let tail = tail[tail.len().saturating_sub(6)..].join("\n");
        if !out.status.success() {
            bail!("{tail}");
        }
        Ok(if start {
            let node = String::from_utf8_lossy(&out.stdout).trim().lines().last().unwrap_or("").to_string();
            format!("running on {node}, its agent answering what it hears")
        } else {
            "stopped, and its node given back".into()
        })
    })();
    match result {
        Ok(detail) => report(if start { "running" } else { "stopped" }, &detail),
        Err(e) => {
            eprintln!("bot {name}: {e:#}");
            report("failed", &format!("{e:#}"));
        }
    }
}

/// The bot's worktree, made or brought up to the project's main.
fn bot_worktree(home: &Path, name: &str) -> Result<PathBuf> {
    static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|p| p.into_inner());
    let repo = checkout(home, None)?;
    let work = home.join(format!("bot-{name}"));
    let git = |dir: &Path, args: &[&str]| -> Result<()> {
        let out = Command::new("git").arg("-C").arg(dir).args(args).stdin(Stdio::null()).output()?;
        if !out.status.success() {
            bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
        }
        Ok(())
    };
    git(&repo, &["fetch", "-q", "origin", "main"])?;
    if work.join(".git").exists() {
        git(&work, &["checkout", "-q", "--force", "--detach", "origin/main"])?;
    } else {
        git(&repo, &["worktree", "add", "-q", "--detach", &work.to_string_lossy(), "origin/main"])?;
    }
    Ok(work)
}

/// `midas sessions list` / `start`.
pub fn list_cmd() -> Result<i32> {
    for m in crate::client::get("/v1/hosted")?.as_array().into_iter().flatten() {
        println!("{:<5} {:<16} {:<18} {}", m["id"].as_str().unwrap_or("?"), m["status"].as_str().unwrap_or("?"),
                 m["branch"].as_str().unwrap_or(""), m["title"].as_str().unwrap_or(""));
    }
    Ok(0)
}

/// `midas sessions create`: exit 0 made, 2 invalid input, 3 a clash, as the hub's 400 and 409.
pub fn create_cmd(name: &str, brief: &str, repo: Option<&str>, base: Option<&str>) -> Result<i32> {
    let brief = if brief == "-" {
        let mut b = String::new();
        std::io::stdin().read_to_string(&mut b).context("reading the brief from stdin")?;
        b
    } else {
        brief.to_string()
    };
    let (code, v) = crate::client::post_raw("/v1/hosted/create", &json!({"name": name, "brief": brief, "repo": repo, "base": base}))?;
    let why = || v["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("the hub answered HTTP {code}"));
    match code {
        200 => {
            let id = v["id"].as_str().ok_or_else(|| anyhow!("the hub gave no id"))?;
            println!("{id} {} {}", v["status"].as_str().unwrap_or("?"), v["branch"].as_str().unwrap_or(""));
            eprintln!("A runner (midas sessions run) picks it up; follow it at {}/{}.", crate::client::hub_url().trim_end_matches('/'),
                      v["page"].as_str().unwrap_or(""));
            Ok(0)
        }
        400 => {
            eprintln!("not created: {}", why());
            Ok(2)
        }
        409 => {
            eprintln!("not created, a conflict: {}", why());
            Ok(3)
        }
        _ => bail!("{}", why()),
    }
}

pub fn start_cmd(prompt: &str, repo: Option<&str>, base: Option<&str>, mode: Option<&str>, model: Option<&str>, agent: Option<&str>) -> Result<i32> {
    // Unsaid, this checkout's project, when it is one.
    let here = || -> Option<String> {
        let r = crate::cli::repo_in(Path::new("."))?;
        let all = crate::client::get("/v1/hosted/projects").ok()?;
        all.as_array()?.iter().any(|p| p["repo"] == r.as_str()).then_some(r)
    };
    let repo = repo.map(str::to_string).or_else(here);
    // Started from within a session: the new one remembers it, for the Map's line between them.
    let from = std::env::var("MIDAS_OWNER").ok().and_then(|o| o.strip_prefix("session-").map(str::to_string));
    let v = crate::client::post("/v1/hosted/start", &json!({"prompt": prompt, "repo": repo, "base": base, "mode": mode, "model": model, "agent": agent, "from": from}))?;
    let id = v["id"].as_str().ok_or_else(|| anyhow!("the hub gave no id"))?;
    eprintln!("{id} queued; a runner (midas sessions run) picks it up. Follow it on the page, Sessions.");
    println!("{id}");
    Ok(0)
}

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

    #[test]
    fn a_log_is_read_on_from_where_the_last_read_ended() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("log.jsonl");
        fs::write(&p, "{\"n\":1}\n{\"n\":2}\nnot json\n{\"n\":3").unwrap();
        // The line still being written is left for the next read.
        let (items, n, end) = read_from(&p, 0, 0, 1);
        assert_eq!((items, n), (vec![json!({"n": 2})], 2));
        assert_eq!(end, 25);
        let mut f = OpenOptions::new().append(true).open(&p).unwrap();
        f.write_all(b"}\n{\"n\":4}\n").unwrap();
        let (items, n, _) = read_from(&p, end, n, 2);
        assert_eq!((items, n), (vec![json!({"n": 3}), json!({"n": 4})], 4));
        // From the start, all of it, as the whole log was read before.
        assert_eq!(read_from(&p, 0, 0, 0).1, 4);
    }

    #[test]
    fn a_logs_tail_begins_at_a_whole_line() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("log.jsonl");
        fs::write(&p, "{\"a\":\"xxxxxxxx\"}\n{\"n\":2}\n").unwrap();
        assert_eq!(last_lines(&p, 9), vec![json!({"n": 2})], "a window just at a line's start");
        assert_eq!(last_lines(&p, 12), vec![json!({"n": 2})], "a window in a line");
        assert_eq!(last_lines(&p, 1 << 20).len(), 2, "a window longer than the file");
        assert!(last_lines(&d.path().join("none"), 10).is_empty());
    }

    #[test]
    fn a_shell_command_is_counted_by_the_program_it_runs() {
        assert_eq!(command_word("cd /x && cargo test -p a").as_deref(), Some("cargo"));
        assert_eq!(command_word("set -e; export A=1; RUST_LOG=x /usr/bin/git log | head").as_deref(), Some("git"));
        assert_eq!(command_word("timeout 60 ssh vps-1 'ls'").as_deref(), Some("ssh"));
        assert_eq!(command_word("for f in a b; do grep x $f; done").as_deref(), Some("grep"));
        assert_eq!(command_word("  "), None);
    }

    #[test]
    fn a_changed_file_is_named_as_its_checkout_names_it() {
        assert_eq!(checkout_path("/home/agent/work/.claude/worktrees/bridge-x/crates/a.rs", "").as_deref(), Some("crates/a.rs"));
        assert_eq!(checkout_path("/home/agent/work/src/b.rs", "/home/agent/work").as_deref(), Some("src/b.rs"));
        assert_eq!(checkout_path("/Users/j/code/midas/web/c.ts", "").as_deref(), Some("web/c.ts"));
        assert_eq!(checkout_path("/home/agent/.claude/projects/-x/memory/m.md", ""), None, "Claude Code's own");
    }

    #[test]
    fn a_tally_counts_what_was_said_and_done() {
        let m = json!({"imported": {"cwd": "/w"}, "created": 0});
        let items = [
            json!({"kind": "user", "text": "fix it", "at": 1000}),
            json!({"kind": "agent", "text": "Looking", "at": 1010}),
            json!({"kind": "agent", "text": " at it", "at": 1010}),
            json!({"kind": "tool", "id": "a", "title": "Bash: cargo test", "input": {"command": "cd /w && cargo fmt && cargo test"}, "at": 1020}),
            json!({"kind": "tool_update", "id": "a", "status": "failed", "at": 1030}),
            json!({"kind": "tool", "id": "b", "title": "Edit", "input": {"file_path": "/w/src/x.rs"}, "at": 1040}),
            json!({"kind": "tool", "id": "c", "title": "Skill", "input": {"skill": "wt:finish-branch"}, "at": 5000}),
            json!({"kind": "user", "text": "thanks", "at": 5010}),
        ];
        let t = tally_of(&m, &items);
        assert_eq!((t["start"].as_i64(), t["end"].as_i64()), (Some(1000), Some(5010)));
        assert_eq!(t["active_s"], 40 + ACTIVE_GAP_S + 10, "the hour's pause counts as ten minutes");
        assert_eq!((t["replies"].as_u64(), t["tool_calls"].as_u64(), t["failed"].as_u64()), (Some(1), Some(3), Some(1)));
        assert_eq!(t["said"], json!([1000, 5010]));
        assert_eq!(t["cargo"], json!({"fmt": 1, "test": 1}));
        assert_eq!(t["commands"], json!({"cargo": 1}));
        assert_eq!(t["files"], json!({"src/x.rs": 1}));
        assert_eq!((t["skills"]["finish-branch"].as_u64(), t["finished"].as_bool()), (Some(1), Some(true)));
    }

    #[test]
    fn a_brief_in_markdown_is_named_by_its_heading_not_its_first_section() {
        assert_eq!(title_of("# Voice agent for calls\n\n## Goal\nDesign it").as_deref(), Some("Voice agent for calls"));
        assert_eq!(title_of("## Goal\nDesign a **voice** agent\n\n## What to do").as_deref(), Some("Design a voice agent"));
        assert_eq!(title_of("fix the sky\nand the sea").as_deref(), Some("fix the sky"));
        assert_eq!(title_of("   \n"), None);
    }

    #[test]
    fn a_session_is_in_one_of_the_workspaces_projects() {
        let names: Vec<String> = ["acme/cartopolis", "acme/podium"].map(String::from).to_vec();
        assert_eq!(project_in(&names, None).unwrap().as_deref(), Some("acme/cartopolis"), "the first, unsaid");
        assert_eq!(project_in(&names, Some("podium")).unwrap().as_deref(), Some("acme/podium"), "by its name");
        assert_eq!(project_in(&names, Some("acme/podium.git")).unwrap().as_deref(), Some("acme/podium"));
        assert!(project_in(&names, Some("acme/midas")).is_err(), "not a project: no runner can go on in it");
        assert!(project_in(&names, Some("../x")).is_err());
        assert_eq!(project_in(&[], None).unwrap(), None, "a workspace without projects: the runner's own checkout");
    }

    #[test]
    fn a_folder_session_takes_projects_as_its_agent_adds_them_and_a_worktree_session_only_its_first() {
        let mut m = json!({"layout": FOLDER, "repo": null, "repos": []});
        assert!(repos_of(&m).is_empty(), "started in none: the agent adds what it needs");
        assert_eq!(take_project(&mut m, "acme/podium"), Some(true));
        assert_eq!(take_project(&mut m, "acme/midas"), Some(true));
        assert_eq!(take_project(&mut m, "acme/podium"), Some(false), "had it already");
        assert_eq!(repos_of(&m), ["acme/podium", "acme/midas"]);
        assert_eq!(m["repo"], "acme/podium", "the first is its project for the list and the board");

        let mut old = json!({"repo": "acme/cartopolis"});
        assert_eq!(repos_of(&old), ["acme/cartopolis"], "one worktree: its one project");
        assert_eq!(take_project(&mut old, "acme/podium"), None, "began before sessions could span projects");
        let mut unsaid = json!({"repo": null});
        assert_eq!(take_project(&mut unsaid, "acme/podium"), Some(true), "an editor's, said on the page");
        assert_eq!(repos_of(&unsaid), ["acme/podium"]);
        // Started between `auto` and folders: no project, and one of these.
        assert!(in_folder(&json!({"auto_project": true, "repo": null})));
    }

    #[test]
    fn a_session_folder_holds_a_worktree_per_project_reported_together_and_each_is_the_sessions() {
        let root = std::env::temp_dir().join(format!("midas-folder-{}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        let git = |dir: &Path, args: &[&str]| crate::util::git(dir, args).unwrap();
        // Two projects, each a remote with a main and a checkout of it.
        let mut checkouts = Vec::new();
        for name in ["podium", "midas"] {
            let origin = root.join("origin/acme").join(format!("{name}.git"));
            fs::create_dir_all(&origin).unwrap();
            git(&origin, &["init", "-q", "--bare", "-b", "main"]);
            let co = root.join("repos").join(name);
            fs::create_dir_all(&co).unwrap();
            git(&co, &["init", "-q", "-b", "main"]);
            fs::create_dir_all(co.join(".claude/skills/shots")).unwrap();
            fs::write(co.join(".claude/skills/shots/SKILL.md"), "x").unwrap();
            fs::write(co.join("README.md"), "hi\n").unwrap();
            git(&co, &["add", "-A"]);
            git(&co, &["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "first"]);
            git(&co, &["remote", "add", "origin", &origin.to_string_lossy()]);
            git(&co, &["push", "-q", "origin", "main"]);
            checkouts.push(co);
        }
        let dir = root.join("session-s9");
        fs::create_dir_all(dir.join(".claude/skills")).unwrap();
        fs::write(dir.join(SESSION_MARK), json!({"id": "s9", "base": "main"}).to_string()).unwrap();
        for co in &checkouts {
            let work = dir.join(co.file_name().unwrap());
            add_worktree(co, &work, "s9", "main").unwrap();
            link_skills(&dir, &work);
            assert_eq!(crate::cli::branch_in(&work).as_deref(), Some("session/s9"));
            assert_eq!(crate::flush::worktree_owner(&work), "session-s9", "a project's worktree is the session's: its nodes and landings");
        }
        assert!(dir.join(".claude/skills/shots/SKILL.md").exists(), "a project's skills, where the agent finds them");
        assert_eq!(crate::flush::worktree_owner(&checkouts[0]), "podium", "a worktree of its own is its own");
        let trees = folder_worktrees(&dir);
        assert_eq!(trees.iter().map(|(r, _)| r.as_str()).collect::<Vec<_>>(), ["acme/podium", "acme/midas"], "in the order made");

        fs::write(dir.join("midas/NEW.md"), "new\n").unwrap();
        let (files, commits) = branch_changes(&dir.join("midas"), "main").unwrap();
        assert_eq!((files.len(), files[0]["path"].as_str(), commits), (1, Some("NEW.md"), 0));
        assert!(branch_changes(&dir.join("podium"), "main").unwrap().0.is_empty());
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_checkout_names_its_project_by_its_directory() {
        let names = vec!["acme/cartopolis".to_string(), "acme/podium".to_string(), "other/podium".to_string(), "acme/midas".to_string()];
        assert_eq!(project_of_dir(&names, Some("/Users/acme/code/midas/")).as_deref(), Some("acme/midas"));
        assert_eq!(project_of_dir(&names, Some("/Users/acme/code/podium")), None, "two projects of that name: no guess");
        assert_eq!(project_of_dir(&names, Some("/home/x/work")), None);
        assert_eq!(project_of_dir(&names, None), None);
    }

    #[test]
    fn an_editors_session_says_which_repository_it_is_in() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("attach-repo");
        let local = json!({"client": "Zed", "machine": "mini", "cwd": "/x", "repo": "acme/podium.git"});
        let id = attach("mini", "zed@mini", "3f4a74a9-0255-4b64-9bbf-66d74efa32c2", "talk", &local, Some("main"), "podium").unwrap()["id"]
            .as_str().unwrap().to_string();
        let m = meta(&id).unwrap();
        assert_eq!(m["repo"], "acme/podium", "what a runner goes on in, handed over");
        assert!(m["local"]["repo"].is_null(), "said once, beside where it runs");
    }

    #[test]
    fn a_meta_read_again_is_the_file_as_it_is_now() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("meta-again");
        let id = start("web:sam", "hello", None, None, None, None, None, &json!(null)).unwrap();
        assert_eq!(meta(&id).unwrap()["status"], "queued");
        update_meta(&id, |m| m["status"] = json!("stopped")).unwrap();
        assert_eq!(list()[0]["status"], "stopped", "replaced through the store");
        // Written in place, by hand: the same inode.
        let path = dir(&id).join("meta.json");
        let was = fs::read_to_string(&path).unwrap();
        fs::write(&path, was.replace("\"stopped\"", "\"failed\"")).unwrap();
        assert_eq!(meta(&id).unwrap()["status"], "failed");
        fs::remove_file(&path).unwrap();
        assert!(meta(&id).is_err() && list().as_array().unwrap().is_empty(), "gone is gone");
    }

    #[test]
    fn a_person_archiving_a_session_open_in_an_editor_ends_it_there() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("archive-done");
        let local = json!({"client": "Zed", "machine": "mini", "cwd": "/x"});
        let v = attach("workstation", "workstation", "3f4a74a9-0255-4b64-9bbf-66d74efa32c2", "talk", &local, Some("main"), "podium").unwrap();
        let id = v["id"].as_str().unwrap().to_string();
        let dones = |id: &str| inbox(id).iter().filter(|i| i["kind"] == "done").count();
        archived_by_person(&id, "web:sam").unwrap();
        assert_eq!(dones(&id), 1, "its mirror is told to end it in the editor");
        // Ended already: nothing left to end.
        update_meta(&id, |m| m["status"] = json!("stopped")).unwrap();
        archived_by_person(&id, "web:sam").unwrap();
        assert_eq!(dones(&id), 1);
        // Only a session in an editor hears "done".
        assert!(tell(&start("web:sam", "hello", None, None, None, None, None, &json!(null)).unwrap(), "done", &json!({}), "web:sam").is_err());
    }

    #[test]
    fn create_queues_a_named_session_with_its_brief_first() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("create");
        let v = create("key:tool", "Snellere tegels", "Maak de tegels sneller.", None, None).unwrap().unwrap();
        let id = v["id"].as_str().unwrap();
        assert_eq!((v["status"].as_str(), v["base"].as_str()), (Some("queued"), Some("main")));
        assert_eq!(v["branch"].as_str().unwrap(), format!("session/{id}"));
        assert_eq!(v["page"].as_str().unwrap(), format!("/sessions/{id}"));
        let m = meta(id).unwrap();
        assert_eq!((m["title"].as_str(), m["layout"].as_str()), (Some("Snellere tegels"), Some(FOLDER)));
        assert!(m["repo"].is_null(), "no project said: its agent adds what it needs");
        let first = inbox(id);
        assert_eq!(first.len(), 1);
        assert_eq!(first[0]["text"], "# Snellere tegels\n\nMaak de tegels sneller.");
        // A brief that names itself keeps its own heading.
        let v = create("key:tool", "Kaart", "# Kaart\n\nTeken de kaart.", None, None).unwrap().unwrap();
        assert_eq!(inbox(v["id"].as_str().unwrap())[0]["text"], "# Kaart\n\nTeken de kaart.");
    }

    #[test]
    fn create_refuses_bad_input_and_a_name_at_work() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("create-refused");
        let invalid = |name: &str, brief: &str, base: Option<&str>| {
            matches!(create("key:tool", name, brief, None, base).unwrap(), Err(Refused::Invalid(_)))
        };
        assert!(invalid("  ", "werk", None));
        assert!(invalid("naam", " \n", None));
        assert!(invalid(&"x".repeat(NAME_MAX + 1), "werk", None));
        assert!(invalid("twee\nregels", "werk", None));
        assert!(invalid("naam", &"x".repeat(BRIEF_MAX + 1), None));
        assert!(invalid("naam", "werk", Some("../main")));
        assert!(invalid("naam", "werk", Some("main;rm")));
        assert!(list().as_array().unwrap().is_empty(), "nothing refused was made");
        assert!(create("key:tool", &"é".repeat(NAME_MAX), "werk", None, None).unwrap().is_ok(), "the limit counts characters");

        let first = create("key:tool", "Tegels", "werk", None, None).unwrap().unwrap();
        let again = create("key:tool", "tegels ", "ander werk", None, None).unwrap();
        assert!(matches!(&again, Err(Refused::Conflict(why)) if why.contains(first["id"].as_str().unwrap())), "{again:?}");
        // Ended, its name is free again.
        update_meta(first["id"].as_str().unwrap(), |m| m["status"] = json!("stopped")).unwrap();
        assert!(create("key:tool", "Tegels", "ander werk", None, None).unwrap().is_ok());
    }

    #[test]
    fn a_branch_is_found_in_a_bare_mirror() {
        let d = tempfile::tempdir().unwrap();
        let git = |args: &[&str]| assert!(Command::new("git").arg("-C").arg(d.path()).args(args).output().unwrap().status.success(), "{args:?}");
        assert!(!has_branch(d.path(), "main"), "no repository: none");
        git(&["init", "-q", "--bare", "-b", "main"]);
        let sha = String::from_utf8(Command::new("git").arg("-C").arg(d.path())
            .args(["-c", "user.name=t", "-c", "user.email=t@t", "commit-tree", "-m", "x", "4b825dc642cb6eb9a060e54bf8d69288fbee4904"])
            .output().unwrap().stdout).unwrap();
        git(&["update-ref", "refs/heads/session/s7", sha.trim()]);
        assert!(has_branch(d.path(), "session/s7"));
        assert!(!has_branch(d.path(), "session/s8"));
    }

    #[test]
    fn what_it_is_doing_reads_as_its_spinner_does() {
        let log = vec![
            json!({"kind": "user", "text": "go"}),
            json!({"kind": "tool", "id": "a", "title": "Read lib.rs", "input": {}}),
            json!({"kind": "tool_update", "id": "a", "status": "completed"}),
            json!({"kind": "tool", "id": "b", "title": "Bash", "input": {"command": "cargo test", "description": "Run the tests"}}),
        ];
        assert_eq!(doing(&log, "working").as_deref(), Some("Run the tests"), "the running tool's description, not its command");
        assert_eq!(doing(&log[..3], "working").as_deref(), Some("Thinking"));
        let writing = [log.clone(), vec![json!({"kind": "tool_update", "id": "b", "status": "completed"}), json!({"kind": "agent", "text": "x"})]].concat();
        assert_eq!(doing(&writing, "working").as_deref(), Some("Writing"));
        assert_eq!(doing(&log, "needs_permission").as_deref(), Some("Waiting for you"));
        assert_eq!(doing(&log, "waiting"), None);
    }

    #[test]
    fn work_in_the_background_keeps_a_session_at_work_and_says_what_it_is() {
        assert_eq!(settled(false, false), "waiting");
        assert_eq!(settled(false, true), "working", "a build in the background is no idle session");
        assert_eq!(settled(true, true), "needs_permission", "asking outranks working");
        let bg = |tasks: Value, turn: bool| background_item(&json!({"sessionId": "s", "tasks": tasks, "turn": turn}));
        assert!(runs_in_background(&json!({"tasks": [], "turn": true})) && !runs_in_background(&json!({"tasks": [], "turn": false})));
        let two = json!([{"id": "b1", "kind": "local_bash", "description": "ssh mac-1 'cargo test'\necho done"}, {"id": "a2", "kind": "local_agent", "description": "Review"}]);
        let log = vec![
            json!({"kind": "user", "text": "test it"}),
            json!({"kind": "tool", "id": "t", "title": "Bash"}),
            bg(two.clone(), false),
            json!({"kind": "tool_update", "id": "t", "status": "completed"}),
        ];
        assert_eq!(doing(&log, "working").as_deref(), Some("Thinking"), "in its turn, the turn is what it does");
        let ended = [log.clone(), vec![json!({"kind": "turn_end"})]].concat();
        assert_eq!(doing(&ended, "working").as_deref(), Some("In the background: ssh mac-1 'cargo test' and 1 more"));
        let woke = [ended.clone(), vec![bg(json!([]), true), json!({"kind": "agent", "text": "Tests pass."})]].concat();
        assert_eq!(doing(&woke, "working").as_deref(), Some("Writing"), "a turn the build woke is no background");
    }

    #[test]
    fn only_what_still_runs_is_given_a_usual_time() {
        let usual = |c: &str| c.starts_with("ssh").then_some(240);
        let mut log = vec![
            json!({"kind": "tool", "id": "t1", "input": {"command": "ssh vps-1 'cargo test'", "run_in_background": true}}),
            json!({"kind": "tool_update", "id": "t1", "status": "completed", "output": "Command running in background with ID: b0j6fa80s. Output is …"}),
            json!({"kind": "background", "tasks": [{"id": "b0j6fa80s", "kind": "local_bash"}]}),
            json!({"kind": "tool", "id": "t2", "input": {"command": "ssh mac-1 'cargo check'"}}),
            json!({"kind": "tool", "id": "t3", "input": {"command": "ls"}}),
        ];
        assert_eq!(json!(expected(&log, usual)), json!({"b0j6fa80s": 240, "t2": 240}), "the task by its id, not the call that started it");
        log.push(json!({"kind": "turn_end"}));
        log.push(json!({"kind": "background", "tasks": []}));
        assert!(expected(&log, usual).is_empty(), "nothing runs");
    }

    #[test]
    fn an_answer_carries_only_the_forms_own_fields() {
        let schema = json!({"type": "object", "properties": {"question_0": {}, "question_0_custom": {}}});
        let r = answer_result(&schema, "accept", &json!({"question_0": "Redis", "question_0_custom": "", "sneaky": "x", "question_1": "y"}));
        assert_eq!(r, json!({"action": "accept", "content": {"question_0": "Redis", "question_0_custom": ""}}));
        assert_eq!(answer_result(&schema, "accept", &json!({"question_0": {"nested": 1}}))["content"], json!({}), "values are text or lists of text");
        assert_eq!(answer_result(&schema, "decline", &json!({})), json!({"action": "decline"}));
        assert_eq!(answer_result(&schema, "whatever", &json!({})), json!({"action": "cancel"}));
    }

    #[test]
    fn a_permission_is_answered_with_an_offered_option_or_cancelled() {
        let opts = json!([{"optionId": "allow", "kind": "allow_once"}, {"optionId": "no", "kind": "reject_once"}]);
        assert_eq!(permission_outcome(&opts, Some("allow")), json!({"outcome": {"outcome": "selected", "optionId": "allow"}}));
        assert_eq!(permission_outcome(&opts, Some("made-up"))["outcome"]["outcome"], "cancelled");
        assert_eq!(permission_outcome(&opts, None)["outcome"]["outcome"], "cancelled");
    }

    #[test]
    fn tool_calls_and_plans_go_in_the_log_and_chatter_does_not() {
        let t = update_item(&json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read lib.rs", "status": "pending"})).unwrap();
        assert_eq!((t["kind"].as_str(), t["title"].as_str()), (Some("tool"), Some("Read lib.rs")));
        assert!(update_item(&json!({"sessionUpdate": "available_commands_update"})).is_none());
        assert!(update_item(&json!({"sessionUpdate": "plan", "entries": []})).is_some());
    }

    #[test]
    fn a_tool_call_keeps_its_command_and_its_output_clipped() {
        let t = update_item(&json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Bash: ls",
                                    "rawInput": {"command": "ls", "description": "List the files"}})).unwrap();
        assert_eq!(t["input"]["description"], "List the files");
        let long = "x".repeat(TOOL_TEXT + 10);
        let u = update_item(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "t1", "status": "completed",
                                    "content": [{"type": "content", "content": {"type": "text", "text": long}}]})).unwrap();
        assert!(u["output"].as_str().unwrap().ends_with("(10 more characters)"));
        let bare = update_item(&json!({"sessionUpdate": "tool_call", "toolCallId": "t2", "title": "Think", "rawInput": {}})).unwrap();
        assert!(bare["input"].is_null(), "nothing given, nothing to unfold");
    }
}