garage44.eu/jeroen/midas

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

.. /src/hook.rs

raw

//! `midas hook post-tool-use`, `user-prompt-submit` and `session-start`: the
//! Claude Code hooks' work, in process. The agent waits for both, after every tool call and
//! before every prompt; as shell scripts they started `jq` up to four times
//! to read their input, and jq 1.6 takes ~45 ms to start — 200 ms a tool
//! call, of which the hub's answer was 6. `hooks/post-tool-use` and
//! `hooks/prompt-submit` only find the binary and hand over to these.
//!
//! The tool hook hands the session any notes the workspace has for it — from another
//! session (`midas say`) or the hub — and the first time the session edits a
//! file, tells the hub (`midas editing`), so an overlap with another session is
//! news now, not at the next flush; after a shell command, and before a
//! prompt, it sends the branch's whole list of changed files in the background
//! (`hook work`, at most once a minute), for what no edit names. Inside a subagent it only tells the hub of
//! edits: the notes are left for the session itself. It FAILS OPEN, and
//! quickly: a hub that does not answer is left alone for a minute.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

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

/// A hub that failed to answer this long ago is not asked again yet.
const DOWN_FOR_S: u64 = 60;

fn down_marker() -> Option<PathBuf> {
    std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache/midas/hub-down"))
}

fn hub_down() -> bool {
    down_marker()
        .and_then(|m| std::fs::metadata(m).ok()?.modified().ok()?.elapsed().ok())
        .is_some_and(|age| age.as_secs() < DOWN_FOR_S)
}

fn mark_down() {
    if let Some(m) = down_marker() {
        if let Some(dir) = m.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        let _ = std::fs::write(m, "");
    }
}

/// `midas <args>` in the background: the agent never waits for it.
fn background(args: &[&str]) {
    if let Ok(me) = std::env::current_exe() {
        let _ = Command::new(me).args(args)
            .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn();
    }
}

fn memory_sync() {
    background(&["memory", "sync", "--quiet"]);
}

/// Every hook's start: nothing if the hub was down a minute ago; else a limit
/// on how long the agent waits, and the hook's input, in the checkout it names
/// (with its git directory).
fn begin() -> Option<(Value, String)> {
    if hub_down() {
        return None;
    }
    // The agent waits at most this long. A hub that takes longer is down for
    // the minute (a caller-key request may otherwise wait 75 s for its answer);
    // anything slow of this machine's own — the `git diff` an edit's report
    // makes — only costs this hook its notes, which the next one brings.
    std::thread::spawn(|| {
        std::thread::sleep(std::time::Duration::from_secs(3));
        if crate::hub::in_flight() {
            mark_down();
        }
        std::process::exit(0);
    });
    let mut text = String::new();
    let _ = std::io::stdin().read_to_string(&mut text);
    let input: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
    let cwd = input["cwd"].as_str().filter(|c| Path::new(c).is_dir())?;
    std::env::set_current_dir(cwd).ok()?;
    // A session's folder, which is no checkout (sessions.rs `folder`), keeps the hooks' marks itself.
    let gitdir = git(&["rev-parse", "--absolute-git-dir"])
        .or_else(|| {
            let marks = Path::new(cwd).join(".midas-hooks");
            (Path::new(cwd).join(crate::sessions::SESSION_MARK).is_file() && std::fs::create_dir_all(&marks).is_ok())
                .then(|| marks.to_string_lossy().to_string())
        })?;
    Some((input, gitdir))
}

fn subagent(input: &Value) -> bool {
    input["agent_id"].as_str().is_some_and(|a| !a.is_empty())
}

/// `midas hook user-prompt-submit`: before every prompt. Names the session
/// after the start of its first prompt (once per worktree; the hub's page
/// shows it instead of the worktree's name), syncs the memory at most every
/// five minutes in the background, and hands the session its notes. A prompt
/// to a teammate or subagent is not the session's: it does neither.
pub fn user_prompt_submit(owner: Option<String>) -> Result<i32> {
    let Some((input, gitdir)) = begin() else { return Ok(0) };
    if subagent(&input) {
        return Ok(0);
    }
    let owner = owner.unwrap_or_else(crate::cli::owner);
    // One the hub runs has its title there, from its first message and its
    // `session_title`; a prompt here would name it after whatever came next
    // (in a new project's worktree, it was the note the hub woke it with).
    let hosted = owner.strip_prefix("session-").is_some_and(crate::sessions::id_ok);
    let labelled = Path::new(&gitdir).join("midas-labelled");
    if !hosted && !labelled.exists() {
        let prompt: String = input["prompt"].as_str().unwrap_or("").chars().take(400).collect();
        // A note midas woke it with, or a background task's end, is no name:
        // the next prompt, the person's own, names it.
        if !prompt.is_empty() && !crate::collab::not_a_name(&prompt) {
            background(&["session", "label", "--text", &prompt]);
            let _ = std::fs::write(&labelled, "");
        }
    }
    background(&["memory", "sync", "--every", "300", "--quiet"]);
    send_work(&gitdir, &owner);
    if crate::collab::notes_cmd(&owner, Some("UserPromptSubmit"), false).is_err() {
        mark_down();
    }
    Ok(0)
}

/// A session's whole list of changed files goes to the hub from its hooks at
/// most this often.
const WORK_EVERY_S: u64 = 60;

/// `midas hook work` in the background, unless it ran here in the last
/// `WORK_EVERY_S`: until it did, a file changed by a shell command reached
/// the hub only with the next `ssh <node>`.
fn send_work(gitdir: &str, owner: &str) {
    let mark = Path::new(gitdir).join("midas-work-sent");
    let recent = std::fs::metadata(&mark).ok().and_then(|m| m.modified().ok()?.elapsed().ok())
        .is_some_and(|age| age.as_secs() < WORK_EVERY_S);
    if !recent && std::fs::write(&mark, "").is_ok() {
        background(&["--owner", owner, "hook", "work"]);
    }
}

/// `midas hook work`: the files this checkout's branch changes, or those of
/// each project in a session's folder, to the hub (`collab::send_work`).
pub fn work(owner: Option<String>) -> Result<i32> {
    let owner = owner.unwrap_or_else(crate::cli::owner);
    let cwd = std::env::current_dir()?;
    let top = git(&["rev-parse", "--show-toplevel"]).map(PathBuf::from);
    let folder = match &top {
        Some(t) => crate::collab::folder_inside(t, &cwd),
        None => Some(cwd.clone()).filter(|d| d.join(crate::sessions::SESSION_MARK).is_file()),
    };
    let tops: Vec<PathBuf> = match (&folder, top) {
        (Some(folder), _) => crate::sessions::folder_worktrees(folder).into_iter().map(|(_, p)| p).collect(),
        (None, Some(top)) => vec![top],
        (None, None) => Vec::new(),
    };
    if folder.is_some() && tops.is_empty() {
        crate::collab::send_no_work(&owner);
    }
    for top in tops {
        crate::collab::send_work(&top, &owner);
    }
    Ok(0)
}

/// A shell command that touches a memory directory (`rm`, `mv` of a note):
/// `/memory` followed by `/` or the end of a word.
fn touches_memory(command: &str) -> bool {
    command.match_indices("/memory").any(|(i, m)| {
        command[i + m.len()..].chars().next().is_none_or(|c| c == '/' || !(c.is_alphanumeric() || c == '_'))
    })
}

/// The file an editing tool changed, if this call was one.
fn edited_file(input: &Value) -> Option<String> {
    let tool = input["tool_name"].as_str()?;
    if !matches!(tool, "Edit" | "Write" | "MultiEdit" | "NotebookEdit") {
        return None;
    }
    let t = &input["tool_input"];
    t["file_path"].as_str().or_else(|| t["notebook_path"].as_str()).filter(|f| !f.is_empty()).map(str::to_string)
}

fn git(args: &[&str]) -> Option<String> {
    Command::new("git").args(args).stderr(Stdio::null()).output().ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

pub fn post_tool_use(owner: Option<String>) -> Result<i32> {
    let Some((input, gitdir)) = begin() else { return Ok(0) };

    // An edit: the file, once per branch (the hub keeps a branch's files until
    // it lands; the flush then keeps them current).
    let mut file = edited_file(&input);
    // A memory note written (Claude Code's projects/<checkout>/memory/): to the
    // hub at once, for every machine's sessions (memory.rs). Not an edit of the
    // worktree's, so not reported as one.
    if file.as_deref().is_some_and(|f| f.contains("/projects/") && f.contains("/memory/") && f.ends_with(".md")) {
        memory_sync();
        file = None;
    }
    // A note removed or moved from the shell: the removal goes too, at once
    // rather than at the next prompt's sync.
    if file.is_none() && input["tool_name"] == "Bash" && touches_memory(input["tool_input"]["command"].as_str().unwrap_or("")) {
        memory_sync();
    }

    // Once per branch and fork point: a landing moves the fork point, and the
    // hub has forgotten the branch's files by then, so a file edited again
    // after it is news again. Marks of an earlier fork point are dropped.
    let seen = Path::new(&gitdir).join("midas-editing");
    let prefix = file.as_deref().map(|f| {
        let dir = Path::new(f).parent().filter(|d| d.is_dir()).unwrap_or(Path::new("."));
        let branch = crate::cli::branch_in(dir).unwrap_or_default();
        format!("{branch} {} ", crate::collab::fork_point(dir).unwrap_or_default())
    }).unwrap_or_default();
    let key = format!("{prefix}{}", file.as_deref().unwrap_or(""));
    let marks = std::fs::read_to_string(&seen).unwrap_or_default();
    let new_file = file.as_ref().filter(|_| !marks.lines().any(|l| l == key));
    let remember = || {
        let mut kept: String = marks.lines().filter(|l| l.starts_with(&prefix)).flat_map(|l| [l, "\n"]).collect();
        kept.push_str(&key);
        kept.push('\n');
        let _ = std::fs::write(&seen, kept);
    };
    let owner = owner.unwrap_or_else(crate::cli::owner);
    // A shell command may have changed files no edit names (sed, git mv, a
    // merge, a generator): the branch's whole list goes to the hub, in the
    // background and at most once a minute, instead of at the next node sync.
    if input["tool_name"] == "Bash" {
        send_work(&gitdir, &owner);
    }

    // Inside a subagent (Claude Code puts `agent_id` in the hook's input): its
    // edits are the session's work, but its notes are not its to read — the
    // parent shares the worktree's name, and a note a subagent took would never
    // reach the agent that can act on it.
    if subagent(&input) {
        if let Some(f) = new_file {
            if crate::collab::editing_cmd(&owner, &[PathBuf::from(f)], None, true).is_ok() {
                remember();
            }
        }
        return Ok(0);
    }
    let asked = match new_file {
        Some(f) => crate::collab::editing_cmd(&owner, &[PathBuf::from(f)], Some("PostToolUse"), false).map(|_| remember()),
        None => crate::collab::notes_cmd(&owner, Some("PostToolUse"), false).map(|_| ()),
    };
    if asked.is_err() {
        mark_down();
    }
    Ok(0)
}

/// What a session is told at its start (`hook session-start`): `@FIRST@`,
/// `@FREE@`, `@TOTAL@`, `@NOTE@` and `@NODES@` are filled in.
const SESSION_START: &str = include_str!("session-start.md");

/// `midas <args>`, its stdout, or nothing if it fails or takes longer than
/// `secs` (it is killed then).
fn ask(args: &[&str], secs: u64) -> Option<String> {
    let me = std::env::current_exe().ok()?;
    let mut child = Command::new(me).args(args)
        .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
    let mut out = child.stdout.take()?;
    let reader = std::thread::spawn(move || {
        let mut s = String::new();
        let _ = out.read_to_string(&mut s);
        s
    });
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
    loop {
        match child.try_wait() {
            Ok(Some(st)) => {
                let s = reader.join().ok()?;
                return st.success().then_some(s);
            }
            Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(5)),
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                return None;
            }
        }
    }
}

/// `midas hook session-start`: tell an agent session how builds work, what the
/// workspace looks like right now, and anything wrong with it. Its five
/// questions — the skills to install, the workspace's state, the ssh config,
/// the node this worktree holds, `midas check` — are asked at once; as a
/// shell script, one after another with seven starts of jq, it took ~570 ms
/// at every start, resume and compaction. FAILS OPEN: anything unexpected
/// costs nothing but this note.
pub fn session_start() -> Result<i32> {
    let mut text = String::new();
    let _ = std::io::stdin().read_to_string(&mut text);
    let input: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
    // The shared skills and these hooks, as this midas carries them. Local
    // files only, and asked before the move to the session's checkout, as the
    // script did.
    let installed = std::thread::spawn(|| ask(&["claude", "install", "--quiet"], 10));
    let Some(cwd) = input["cwd"].as_str().filter(|c| Path::new(c).is_dir()) else { return Ok(0) };
    std::env::set_current_dir(cwd)?;
    // For the history of how long sessions take (the hub's web page).
    // Loaded again by midas's runner (MIDAS_REVIVED, sessions.rs `run_session`) is a revival,
    // which the board does not count as a start; a person's own `--resume` stays "resume".
    let revived = std::env::var("MIDAS_REVIVED").is_ok_and(|v| v == "1");
    match input["source"].as_str().filter(|s| !s.is_empty()) {
        Some("resume") if revived => background(&["session", "start", "--reason", "revive"]),
        Some(why) => background(&["session", "start", "--reason", why]),
        None => background(&["session", "start"]),
    }
    let ssh_config = std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".ssh/config").to_string_lossy().to_string());
    let (state, held, problems) = std::thread::scope(|s| {
        // The ssh blocks and host keys for every node, from the hub: a node
        // added or set up again is reachable without anybody editing ~/.ssh.
        if let Some(cfg) = &ssh_config {
            s.spawn(move || ask(&["ssh-config", "--flush", "--write", cfg], 5));
        }
        let held = s.spawn(|| ask(&["mine"], 5));
        let problems = s.spawn(|| ask(&["check"], 8));
        let state = ask(&["status", "--json"], 5);
        (state, held.join().ok().flatten(), problems.join().ok().flatten())
    });
    let Some(state) = state.and_then(|s| serde_json::from_str::<Value>(&s).ok()) else { return Ok(0) };
    let held = held.and_then(|h| serde_json::from_str::<Value>(&h).ok())
        .and_then(|v| v["id"].as_str().map(str::to_string));
    let installed = installed.join().ok().flatten().unwrap_or_default();
    println!("{}", json!({"hookSpecificOutput": {
        "hookEventName": "SessionStart",
        "additionalContext": session_start_text(&state, held.as_deref(), &problems.unwrap_or_default(), &installed),
    }}));
    Ok(0)
}

fn session_start_text(state: &Value, held: Option<&str>, check: &str, installed: &str) -> String {
    let nodes = state["nodes"].as_array().cloned().unwrap_or_default();
    let enabled = |n: &&Value| n["enabled"] == true;
    let total = nodes.iter().filter(enabled).count();
    let free = nodes.iter().filter(enabled)
        .filter(|n| n["drained"] != true && n["id"].as_str().is_none_or(|id| state["leases"][id].is_null()))
        .count();
    let list: Vec<String> = nodes.iter().map(|n| format!(
        "- `{}` on {}: {}{}{}",
        n["id"].as_str().unwrap_or("?"), n["machine"].as_str().unwrap_or("?"), n["renderer"].as_str().unwrap_or("?"),
        if n["gpu"] == true { " -- hardware GPU" } else { "" },
        if n["enabled"] == true { "" } else { " (out of the pool right now)" },
    )).collect();
    let first = match held {
        Some(h) => format!("You hold `{h}`: `ssh {h} 'cargo …'`."),
        None => "You hold no node.".into(),
    };
    let mut note = String::new();
    let problems: Vec<String> = check.lines().filter(|l| l.contains('✗'))
        .map(|l| format!("- {}", l.trim_start().trim_start_matches('✗').trim_start())).collect();
    if !problems.is_empty() {
        note += &format!("\n\n**Workspace problems right now** (`midas check` for the full report):\n{}", problems.join("\n"));
    }
    let installed: Vec<String> = installed.lines().filter(|l| !l.is_empty()).map(|l| format!("- {l}")).collect();
    if !installed.is_empty() {
        note += &format!("\n\n**midas updated the shared skills in ~/.claude** (`midas claude install`):\n{}", installed.join("\n"));
    }
    SESSION_START.trim_end()
        .replace("@FIRST@", &first)
        .replace("@FREE@", &free.to_string())
        .replace("@TOTAL@", &total.to_string())
        .replace("@NOTE@", &note)
        .replace("@NODES@", &list.join("\n"))
}

/// `midas hook pre-tool-use`: before a "Shall it land?" card, a picture shown
/// since the person last answered (`midas show`, the `show` tool), or the card
/// itself saying why there is none ("No picture: …", "Geen beeld: …", in the
/// question or an option's description). Not the evidence above it: the text of
/// the message that makes the call reaches the transcript only after the call,
/// so a hook never sees it (found the day it landed, 2026-11-27). Also a line in
/// an earlier message of the turn.
///
/// The skill asked for one and 25 of 190 landing cards answered "not yet" in the
/// month to 2026-11-27 were the person asking for it ("shots", "geen shot
/// gezien"). Every other call passes, and so does anything it cannot read.
pub fn pre_tool_use() -> Result<i32> {
    let mut text = String::new();
    let _ = std::io::stdin().read_to_string(&mut text);
    let input: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
    if input["tool_name"] != "AskUserQuestion" || subagent(&input) {
        return Ok(0);
    }
    let asked = input["tool_input"]["questions"].to_string();
    let Some(transcript) = input["transcript_path"].as_str().and_then(|p| std::fs::read_to_string(p).ok()) else { return Ok(0) };

    if may_ask(&asked, &transcript) {
        return Ok(0);
    }
    println!("{}", json!({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
        "permissionDecisionReason": "A landing question needs a picture shown first (finish-branch: `midas show`, before / after / \
            reference side by side; a ground-level or oblique view for anything in the world, the phone's viewport for UI). Look at \
            it yourself before showing it. When nothing in the change can be seen, say so in the card itself — the question or the \
            recommended option's description — as \
            \"No picture: <why>\", and ask again."}}));
    Ok(0)
}

/// Is this card let through: not a landing card, or one that says why it has
/// no picture, or one with a picture shown since the person last answered.
fn may_ask(asked: &str, transcript: &str) -> bool {
    let a = asked.to_lowercase();
    !landing_question(asked) || a.contains("no picture:") || a.contains("geen beeld:") || pictured(transcript)
}

fn landing_question(asked: &str) -> bool {
    let a = asked.to_lowercase();
    a.contains("shall it land") || a.contains("land it") || a.contains("landen") || a.contains("zal het landen")
}

/// Since the person last spoke (a prompt, or an answer to a card): was a
/// picture shown, or its absence said?
fn pictured(transcript: &str) -> bool {
    for line in transcript.lines().rev() {
        let Ok(o) = serde_json::from_str::<Value>(line) else { continue };
        let content = &o["message"]["content"];
        match o["type"].as_str() {
            Some("assistant") => for c in content.as_array().into_iter().flatten() {
                let shown = c["type"] == "tool_use" && (c["name"].as_str().is_some_and(|n| n.ends_with("__show"))
                    || c["input"]["command"].as_str().is_some_and(|s| s.contains("midas show")));
                let said = c["type"] == "text" && c["text"].as_str().is_some_and(|t| t.lines().any(|l| {
                    let l = l.trim_start_matches(['*', '-', ' ', '_']).to_lowercase();
                    l.starts_with("no picture:") || l.starts_with("geen beeld:")
                }));
                if shown || said {
                    return true;
                }
            },
            Some("user") if o["isMeta"] != true => {
                let prompt = content.is_string() && !content.as_str().unwrap_or("").starts_with('<')
                    || content.as_array().is_some_and(|a| a.iter().any(|c| c["type"] == "text"));
                let answer = content.as_array().is_some_and(|a| a.iter().any(|c| c["type"] == "tool_result"
                    && { let s = c["content"].to_string(); s.contains("answered your questions") || s.contains("user answered") }));
                if prompt || answer {
                    return false;
                }
            }
            _ => {}
        }
    }
    false
}

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

    #[test]
    fn a_landing_card_waits_for_a_picture_since_the_last_answer() {
        let prompt = json!({"type": "user", "message": {"content": "make the roofs red"}}).to_string();
        let show = json!({"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "mcp__midas__show", "input": {"path": "/tmp/a.png"}}]}}).to_string();
        let bash_show = json!({"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "Bash", "input": {"command": "midas show x.png --caption after"}}]}}).to_string();
        let none = json!({"type": "assistant", "message": {"content": [{"type": "text", "text": "Evidence:\n- **No picture:** a server fix, nothing drawn"}]}}).to_string();
        let edit = json!({"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "Edit", "input": {}}]}}).to_string();
        let result = json!({"type": "user", "message": {"content": [{"type": "tool_result", "content": "ok"}]}}).to_string();
        let answer = json!({"type": "user", "message": {"content": [{"type": "tool_result", "content": "The user answered: \"Shall it land?\"=\"not yet, greener\""}]}}).to_string();
        let t = |l: &[&str]| l.join("\n");
        assert!(!pictured(&t(&[&prompt, &edit, &result])), "nothing shown");
        assert!(pictured(&t(&[&prompt, &show, &result, &edit, &result])));
        assert!(pictured(&t(&[&prompt, &bash_show, &result])));
        assert!(pictured(&t(&[&prompt, &none])), "its absence said");
        assert!(!pictured(&t(&[&prompt, &show, &result, &answer, &edit, &result])), "shown before the person's last answer");
        assert!(landing_question(r#"[{"question":"Shall it land? cartopolis, session/s1"}]"#));
        assert!(landing_question(r#"[{"header":"Landen","question":"Zal het landen?"}]"#));
        assert!(!landing_question(r#"[{"header":"Logo","question":"Which logo?"}]"#));
        // The card says why it has none: the evidence above it is not in the transcript yet.
        let card = r#"[{"question":"Shall it land? x","options":[{"label":"Land it","description":"No picture: a build script"}]}]"#;
        assert!(may_ask(card, &t(&[&prompt, &edit, &result])));
        assert!(!may_ask(r#"[{"question":"Shall it land? x"}]"#, &t(&[&prompt, &edit, &result])));
    }

    #[test]
    fn a_shell_command_touches_memory_only_at_a_word_end() {
        assert!(touches_memory("rm ~/.claude/projects/x/memory/a.md"));
        assert!(touches_memory("ls /home/agent/memory"));
        assert!(touches_memory("cd /x/memory && ls"));
        assert!(!touches_memory("cat /proc/memory_info"));
        assert!(!touches_memory("ls src/memoryless"));
        assert!(!touches_memory("cargo test"));
    }

    #[test]
    fn only_editing_tools_name_a_file() {
        let edit: Value = serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "/a/b.rs"}});
        let nb: Value = serde_json::json!({"tool_name": "NotebookEdit", "tool_input": {"notebook_path": "/a/n.ipynb"}});
        let read: Value = serde_json::json!({"tool_name": "Read", "tool_input": {"file_path": "/a/b.rs"}});
        assert_eq!(edited_file(&edit).as_deref(), Some("/a/b.rs"));
        assert_eq!(edited_file(&nb).as_deref(), Some("/a/n.ipynb"));
        assert_eq!(edited_file(&read), None);
    }

    #[test]
    fn the_session_start_note_counts_free_nodes_and_names_the_held_one() {
        let state = serde_json::json!({
            "nodes": [
                {"id": "a-1", "machine": "a", "renderer": "llvmpipe", "enabled": true},
                {"id": "b-1", "machine": "b", "renderer": "RADV", "gpu": true, "enabled": true},
                {"id": "c-1", "machine": "c", "renderer": "M5", "enabled": true, "drained": true},
                {"id": "d-1", "machine": "d", "renderer": "?", "enabled": false},
            ],
            "leases": {"a-1": {"owner": "s"}},
        });
        let t = session_start_text(&state, Some("a-1"), "  ✗ hub: old build\n  · fine\n", "skills/x\n");
        assert!(t.starts_with("**Builds run on a build node, over ssh.** You hold `a-1`: `ssh a-1 'cargo …'`. 1 of 3 nodes free."));
        assert!(t.contains("**Workspace problems right now** (`midas check` for the full report):\n- hub: old build\n\n**midas updated"));
        assert!(t.contains("- `b-1` on b: RADV -- hardware GPU\n"));
        assert!(t.contains("- `d-1` on d: ? (out of the pool right now)"));
        for p in ["@FIRST@", "@FREE@", "@TOTAL@", "@NOTE@", "@NODES@"] {
            assert!(!t.contains(p), "{p} left in: {t}");
        }
    }
}

// ── A session folder's projects' own hooks ───────────────────────────────────
//
// Claude Code loads a project's hooks (`.claude/settings.json`) from the
// directory the agent starts in. A session spanning projects starts in its own
// folder, which is none of them (sessions.rs `folder`), so the folder's
// settings name one hook per event, this one, which hands the event to the
// hooks of the projects it concerns: an edit's to its file's project, a shell
// command's to the project it runs in, the rest to every project. A project
// added later is found then, with nothing to reload. Each hook runs as Claude
// Code would run it — `CLAUDE_PROJECT_DIR` its worktree, the event's input on
// stdin, its timeout — and their answers are put together as one.

/// The events a session folder hands to its projects' hooks. SessionStart is
/// not one: a project's start hooks run when it is added (`start_project`).
pub const PROJECT_EVENTS: &[&str] = &["PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop", "SubagentStop", "PreCompact", "Notification", "SessionEnd"];

/// The folder's own settings (`.claude/settings.json`): its projects' hooks
/// through `midas hook projects`, and the open ends left for this machine at
/// the start (`midas todo take`, as the session's own: a project's start hook
/// would take them in the project's name).
pub fn folder_settings() -> Value {
    let run = |args: &str| format!("M=\"$HOME/.local/bin/midas\"; [ -x \"$M\" ] || M=midas; exec \"$M\" {args}");
    let mut hooks = serde_json::Map::new();
    for e in PROJECT_EVENTS {
        hooks.insert(e.to_string(), json!([{"hooks": [{"type": "command", "command": run(&format!("hook projects {e}")), "timeout": 120}]}]));
    }
    hooks.insert("SessionStart".into(), json!([{"hooks": [{"type": "command", "command": run("todo take --hook SessionStart"), "timeout": 10}]}]));
    json!({"hooks": hooks})
}

/// What one hook said: its exit code, stdout and stderr.
struct Said {
    code: i32,
    out: String,
    err: String,
}

/// Whether a hook entry's `matcher` takes `tool`: Claude Code's are regular
/// expressions, and the ones projects write are a name, names joined by `|`,
/// `*` or nothing for every tool, or a prefix ending in `.*`.
fn matches(matcher: Option<&str>, tool: Option<&str>) -> bool {
    let Some(m) = matcher.map(str::trim).filter(|m| !m.is_empty() && *m != "*" && *m != ".*") else { return true };
    let Some(tool) = tool else { return true };
    m.split('|').map(str::trim).any(|alt| match alt.strip_suffix(".*") {
        Some(prefix) => tool.starts_with(prefix),
        None => alt == tool,
    })
}

/// The hooks project worktree `tree` has for `event`, each as (command,
/// timeout in seconds), for `tool` — from its `.claude/settings.json` as it is
/// **on the project's main**, and only when the worktree's copy is that one.
///
/// Claude Code has the person look at a project's hook changes before it runs
/// them; this relay has nobody to ask, and runs in the runner's account with
/// its environment. A branch that edits the file (a session's own, or a
/// project a prompt had it add) would otherwise run on the runner at the next
/// tool call, before anyone read the diff. Landed is what counts as read.
/// `settings.local.json` is nobody's reviewed file and is never run.
fn hooks_of(tree: &Path, event: &str, tool: Option<&str>) -> Vec<(String, u64)> {
    let mut found = Vec::new();
    let Some(text) = landed_settings(tree) else { return found };
    let Ok(v) = serde_json::from_str::<Value>(&text) else { return found };
    for entry in v["hooks"][event].as_array().into_iter().flatten() {
        if !matches(entry["matcher"].as_str(), tool) {
            continue;
        }
        for h in entry["hooks"].as_array().into_iter().flatten().filter(|h| h["type"] == "command") {
            if let Some(c) = h["command"].as_str() {
                found.push((c.to_string(), h["timeout"].as_u64().unwrap_or(60).clamp(1, 600)));
            }
        }
    }
    found
}

/// `.claude/settings.json` of `tree` when it is exactly the one on the
/// project's main (`origin/main`, or `main` in a checkout with no origin);
/// None, and a line on stderr, when the worktree's differs or main has none.
fn landed_settings(tree: &Path) -> Option<String> {
    let working = std::fs::read_to_string(tree.join(".claude/settings.json")).ok()?;
    let landed = ["origin/main", "main"].iter().find_map(|r| {
        let out = Command::new("git").args(["-C"]).arg(tree).args(["show", &format!("{r}:.claude/settings.json")])
            .stdin(Stdio::null()).output().ok()?;
        out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
    })?;
    if landed != working {
        eprintln!("midas: {}/.claude/settings.json differs from main's: its hooks run once that lands", tree.display());
        return None;
    }
    Some(working)
}

/// A pipe read to its end on a thread of its own; what it read comes on the channel.
fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> std::sync::mpsc::Receiver<String> {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut s = String::new();
        if let Some(mut p) = pipe {
            let _ = p.read_to_string(&mut s);
        }
        let _ = tx.send(s);
    });
    rx
}

/// Run one hook as Claude Code would, in its project's worktree.
///
/// In a process group of its own, which a timeout kills whole: killing the `sh` alone left what it
/// started holding the pipes, and reading them to their end waited on that for good. Something the
/// hook leaves running in the background (`foo &`) keeps them open too, so its output is waited for
/// only briefly once the hook itself has ended.
fn run_hook(tree: &Path, command: &str, timeout: u64, input: &str) -> Said {
    use std::io::Write;
    use std::os::unix::process::CommandExt;
    // Without the hub key: a project's hook reads the session's input, not the workspace's credential.
    let child = Command::new("sh").arg("-c").arg(command).current_dir(tree).env("CLAUDE_PROJECT_DIR", tree)
        .env_remove("MIDAS_HUB_KEY")
        .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).spawn();
    let Ok(mut child) = child else { return Said { code: 1, out: String::new(), err: format!("could not run {command}") } };
    if let Some(mut stdin) = child.stdin.take() {
        let input = input.to_string();
        std::thread::spawn(move || stdin.write_all(input.as_bytes()));
    }
    let (out, err) = (drain(child.stdout.take()), drain(child.stderr.take()));
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout);
    let code = loop {
        match child.try_wait() {
            Ok(Some(st)) => break st.code().unwrap_or(1),
            Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(10)),
            _ => {
                // SAFETY: a signal to the group this child leads, made for it above.
                unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL) };
                let _ = child.wait();
                break 1;
            }
        }
    };
    let grace = std::time::Duration::from_secs(1);
    Said { code, out: out.recv_timeout(grace).unwrap_or_default(), err: err.recv_timeout(grace).unwrap_or_default() }
}

/// Many hooks' answers as one, as Claude Code reads a hook's: exit 2 (its
/// stderr to the agent, a block) if any said so; else their JSON merged —
/// every `additionalContext`, joined, and of any other field the first said —
/// with plain output added as context where Claude Code would give it to the
/// agent (a prompt's), or else passed on as it is. Returns (exit, stdout, stderr).
fn merge(event: &str, said: &[Said]) -> (i32, String, String) {
    let blocked: Vec<&str> = said.iter().filter(|s| s.code == 2).map(|s| s.err.trim()).filter(|e| !e.is_empty()).collect();
    if said.iter().any(|s| s.code == 2) {
        return (2, String::new(), blocked.join("\n"));
    }
    let (mut top, mut specific) = (serde_json::Map::new(), serde_json::Map::new());
    let (mut context, mut plain) = (Vec::new(), Vec::new());
    for s in said.iter().filter(|s| s.code == 0) {
        let text = s.out.trim();
        match serde_json::from_str::<Value>(text) {
            Ok(Value::Object(o)) => {
                for (k, v) in o {
                    if k == "hookSpecificOutput" {
                        for (k, v) in v.as_object().into_iter().flatten() {
                            if k == "additionalContext" {
                                context.extend(v.as_str().map(str::to_string));
                            } else {
                                specific.entry(k.clone()).or_insert(v.clone());
                            }
                        }
                    } else {
                        top.entry(k).or_insert(v);
                    }
                }
            }
            _ if !text.is_empty() => plain.push(text.to_string()),
            _ => {}
        }
    }
    if event == "UserPromptSubmit" {
        context.append(&mut plain);
    }
    if top.is_empty() && specific.is_empty() && context.is_empty() {
        return (0, plain.join("\n"), String::new());
    }
    if !context.is_empty() {
        specific.insert("additionalContext".into(), json!(context.join("\n\n")));
    }
    if !specific.is_empty() {
        specific.insert("hookEventName".into(), json!(event));
        top.insert("hookSpecificOutput".into(), Value::Object(specific));
    }
    (0, Value::Object(top).to_string(), String::new())
}

/// The project worktrees an event concerns: a tool's file's, or the one a
/// command runs in; every project's for any other event or tool.
fn concerned<'a>(trees: &'a [(String, PathBuf)], input: &Value) -> Vec<&'a (String, PathBuf)> {
    let t = &input["tool_input"];
    let file = t["file_path"].as_str().or_else(|| t["notebook_path"].as_str()).or_else(|| t["path"].as_str());
    let within = |p: &Path| trees.iter().find(|(_, tree)| p.starts_with(tree));
    if let Some(hit) = file.map(Path::new).and_then(within) {
        return vec![hit];
    }
    if input["tool_name"].is_string() {
        if let Some(hit) = input["cwd"].as_str().map(Path::new).and_then(within) {
            return vec![hit];
        }
    }
    trees.iter().collect()
}

/// `midas hook projects <event>`: hand a session folder's event to its
/// projects' own hooks. FAILS OPEN: outside a session's folder, or with no
/// project hooks, it says nothing.
pub fn projects(event: &str) -> Result<i32> {
    let mut text = String::new();
    let _ = std::io::stdin().read_to_string(&mut text);
    let input: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
    let Some(folder) = input["cwd"].as_str().map(Path::new)
        .and_then(|c| c.ancestors().find(|d| d.join(crate::sessions::SESSION_MARK).is_file())) else { return Ok(0) };
    let trees = crate::sessions::folder_worktrees(folder);
    let tool = input["tool_name"].as_str();
    let said: Vec<Said> = concerned(&trees, &input).into_iter()
        .flat_map(|(_, tree)| hooks_of(tree, event, tool).into_iter().map(move |(c, t)| (tree, c, t)))
        .map(|(tree, c, t)| run_hook(tree, &c, t, &text)).collect();
    let (code, out, err) = merge(event, &said);
    if !out.is_empty() {
        println!("{out}");
    }
    if !err.is_empty() {
        eprintln!("{err}");
    }
    Ok(code)
}

/// A project's own start hooks, run as it is added to a session folder
/// (`sessions::add_project`): what they would have told the agent at its
/// start, for the tool's answer. The input is the session's (its folder the
/// `cwd`); `CLAUDE_PROJECT_DIR` is the project's worktree.
pub fn start_project(folder: &Path, tree: &Path) -> Option<String> {
    let input = json!({"hook_event_name": "SessionStart", "source": "startup", "cwd": folder}).to_string();
    let said: Vec<Said> = hooks_of(tree, "SessionStart", None).into_iter().map(|(c, t)| run_hook(tree, &c, t, &input)).collect();
    let (_, out, _) = merge("SessionStart", &said);
    let v: Value = serde_json::from_str(&out).unwrap_or(Value::Null);
    let context = v["hookSpecificOutput"]["additionalContext"].as_str().map(str::to_string).unwrap_or(out);
    Some(context.trim().to_string()).filter(|c| !c.is_empty())
}

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

    fn said(code: i32, out: &str, err: &str) -> Said {
        Said { code, out: out.into(), err: err.into() }
    }

    #[test]
    fn a_matcher_takes_the_tools_a_project_names() {
        assert!(matches(Some("Read|Edit|Write"), Some("Edit")));
        assert!(!matches(Some("Read|Edit|Write"), Some("Bash")));
        assert!(matches(Some("mcp__midas__.*"), Some("mcp__midas__show")));
        assert!(matches(Some("*"), Some("Bash")) && matches(None, Some("Bash")) && matches(Some(""), Some("Bash")));
        assert!(matches(Some("Bash"), None), "an event of no tool: every entry");
    }

    #[test]
    fn an_event_goes_to_the_project_its_file_or_command_is_in_else_to_every_one() {
        let trees = vec![("acme/podium".to_string(), PathBuf::from("/s/session-s9/podium")),
                         ("acme/midas".to_string(), PathBuf::from("/s/session-s9/midas"))];
        let names = |v: Vec<&(String, PathBuf)>| v.into_iter().map(|(r, _)| r.clone()).collect::<Vec<String>>();
        let edit = json!({"tool_name": "Edit", "cwd": "/s/session-s9", "tool_input": {"file_path": "/s/session-s9/midas/src/a.rs"}});
        assert_eq!(names(concerned(&trees, &edit)), ["acme/midas"]);
        let bash = json!({"tool_name": "Bash", "cwd": "/s/session-s9/podium/web", "tool_input": {"command": "bun test"}});
        assert_eq!(names(concerned(&trees, &bash)), ["acme/podium"]);
        let prompt = json!({"cwd": "/s/session-s9/podium", "prompt": "hi"});
        assert_eq!(names(concerned(&trees, &prompt)).len(), 2, "not a tool's: every project's");
    }

    #[test]
    fn several_hooks_answer_as_one() {
        let a = r#"{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"notes for a.rs"}}"#;
        let b = r#"{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"more"},"systemMessage":"hi"}"#;
        let (code, out, _) = merge("PostToolUse", &[said(0, a, ""), said(0, b, ""), said(0, "", "")]);
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!((code, v["hookSpecificOutput"]["additionalContext"].as_str(), v["systemMessage"].as_str()), (0, Some("notes for a.rs\n\nmore"), Some("hi")));
        let (code, out, err) = merge("PreToolUse", &[said(0, a, ""), said(2, "", "not that file")]);
        assert_eq!((code, out.as_str(), err.as_str()), (2, "", "not that file"), "one block blocks");
        let (_, out, _) = merge("UserPromptSubmit", &[said(0, "remember the routing note", "")]);
        assert!(out.contains("remember the routing note") && out.contains("additionalContext"), "a prompt's plain output is context");
        assert_eq!(merge("Stop", &[said(1, "x", "y")]), (0, String::new(), String::new()), "a failing hook says nothing");
    }

    #[test]
    fn a_projects_hooks_run_in_its_worktree_with_its_own_dir_once_landed() {
        let tree = std::env::temp_dir().join(format!("midas-project-hooks-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tree);
        std::fs::create_dir_all(tree.join(".claude")).unwrap();
        let settings = json!({"hooks": {"PostToolUse": [
            {"matcher": "Read|Edit", "hooks": [{"type": "command", "command": "printf '%s' \"$CLAUDE_PROJECT_DIR\"; cat >/dev/null", "timeout": 5}]},
            {"matcher": "Bash", "hooks": [{"type": "command", "command": "echo never"}]},
        ]}}).to_string();
        std::fs::write(tree.join(".claude/settings.json"), &settings).unwrap();
        assert!(hooks_of(&tree, "PostToolUse", Some("Edit")).is_empty(), "not in any checkout: nothing landed, nothing runs");
        let git = |args: &[&str]| {
            let st = Command::new("git").args(["-C"]).arg(&tree).args(["-c", "user.name=t", "-c", "user.email=t@example.org"])
                .args(args).stdout(Stdio::null()).stderr(Stdio::null()).status().unwrap();
            assert!(st.success(), "git {args:?}");
        };
        git(&["init", "-q", "-b", "main"]);
        git(&["add", ".claude/settings.json"]);
        git(&["commit", "-q", "-m", "hooks"]);
        let hooks = hooks_of(&tree, "PostToolUse", Some("Edit"));
        assert_eq!(hooks.len(), 1, "landed on main: its hooks run");
        let s = run_hook(&tree, &hooks[0].0, hooks[0].1, "{}");
        assert_eq!((s.code, s.out), (0, tree.to_string_lossy().to_string()));
        // The branch edits the file: its hooks wait until that lands.
        std::fs::write(tree.join(".claude/settings.json"), settings.replace("echo never", "echo now")).unwrap();
        assert!(hooks_of(&tree, "PostToolUse", Some("Edit")).is_empty(), "an unlanded change runs nothing, not even the unchanged entries");
        std::fs::write(tree.join(".claude/settings.local.json"), &settings).unwrap();
        assert!(hooks_of(&tree, "PostToolUse", Some("Edit")).is_empty(), "local settings are nobody's reviewed file");
        assert!(folder_settings()["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str().unwrap().contains("hook projects PostToolUse"));
        let _ = std::fs::remove_dir_all(&tree);
    }

    #[test]
    fn a_hook_that_leaves_something_running_does_not_hang_its_session() {
        let tree = std::env::temp_dir();
        let t = std::time::Instant::now();
        // Ends at once, but what it started holds its stdout for a minute.
        let s = run_hook(&tree, "echo said; sleep 60 &", 5, "");
        assert_eq!(s.code, 0);
        // Runs past its limit, with a child of its own holding the pipes.
        let s = run_hook(&tree, "sleep 60 & sleep 60", 1, "");
        assert_eq!(s.code, 1);
        assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed());
    }
}