//! Questions about the code, for the voice (discuss.rs). The realtime model //! cannot read a repository, and reasons poorly about one when it is shown //! bits of it; so it hands a question to Claude Code, which reads the code and //! answers in a few spoken sentences, and goes on talking meanwhile. //! //! The page asks the hub (`POST /v1/hosted/discuss/ask`, the `steer` role, as //! the call is), the sessions runner takes the question with its next poll //! (`asks`), answers it, and says the answer back (`/v1/hosted/runner/answer`); //! the page waits for it (`/v1/hosted/discuss/answer`, a long poll) and gives //! it to the voice. Claude Code runs there read-only (`--restricted`, only //! Read, Grep and Glob, no MCP servers, no settings files), in a worktree of //! the project's main as it is now, `ask-`, or in the session's own //! worktree when the question is about one the runner has. The questions are //! kept in memory only: a hub restarted meanwhile loses them, and the page says //! the question went unanswered. use std::collections::BTreeMap; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::{Condvar, Mutex}; use std::time::{Duration, Instant}; use anyhow::{bail, Context, Result}; use serde_json::{json, Value}; use crate::registry::now; /// The longest question a page may hand on. const QUESTION_MAX: usize = 4000; /// How long a question may wait for a runner to take it, and then for its answer. const TAKE_S: i64 = 60; const ANSWER_S: i64 = 300; /// How long an answered question is kept for the page to fetch. const KEEP_S: i64 = 900; /// How long Claude Code may read before the question is given up on. const RUN_S: u64 = 240; /// The model that answers, unless the runner's `MIDAS_ASK_MODEL` names another: /// the voice waits on it, so a fast one. const MODEL: &str = "sonnet"; /// How the answer is to be put: it is read out on a phone. const STYLE: &str = "You answer one question about this repository for a voice assistant, which reads your answer out loud to a person \ on a phone. Read the code to answer: never guess, and say so when the code does not settle it. Answer in at most five short spoken \ sentences of plain prose: no Markdown, no lists, no code, no line numbers. Name a file or a function only when it helps them find \ it, by its plain name. Lead with the answer itself. You cannot change anything and must not try."; #[derive(Clone, Debug)] struct Ask { question: String, repo: String, session: Option, /// queued, asked (a runner has it), answered, failed. state: &'static str, answer: String, at: i64, } static ASKS: (Mutex>, Condvar) = (Mutex::new(BTreeMap::new()), Condvar::new()); fn asks() -> std::sync::MutexGuard<'static, BTreeMap> { ASKS.0.lock().unwrap_or_else(|p| p.into_inner()) } /// Questions nobody took or answered in time fail; old answers go. fn sweep(all: &mut BTreeMap) { let t = now(); for a in all.values_mut() { if a.state == "queued" && a.at + TAKE_S <= t { a.state = "failed"; a.answer = "no sessions runner took the question".into(); } else if a.state == "asked" && a.at + ANSWER_S <= t { a.state = "failed"; a.answer = "the runner gave no answer in time".into(); } } all.retain(|_, a| a.at + KEEP_S > t); } /// A question from the page: its id, for [`wait`]. `session`: about that /// session's code, in its own worktree, and its project when `repo` names none. pub fn ask(question: &str, repo: Option<&str>, session: Option<&str>, by: &str) -> Result { let question = question.trim(); if question.is_empty() { bail!("an empty question"); } if question.len() > QUESTION_MAX { bail!("a question of at most {QUESTION_MAX} bytes"); } let session = session.map(str::trim).filter(|s| !s.is_empty()); let mut repo = repo.map(str::trim).filter(|r| !r.is_empty()).map(str::to_string); if let Some(s) = session { let m = crate::sessions::meta(s).with_context(|| format!("no session {s}"))?; if repo.is_none() { repo = m["repo"].as_str().filter(|r| !r.is_empty()).map(str::to_string); } } let repo = crate::sessions::project_of(repo.as_deref())?.context("the workspace has no projects")?; let mut all = asks(); sweep(&mut all); let id = loop { let id = format!("q{}", rand_u32()); if !all.contains_key(&id) { break id; } }; all.insert(id.clone(), Ask { question: question.into(), repo: repo.clone(), session: session.map(str::to_string), state: "queued", answer: String::new(), at: now() }); drop(all); crate::events::emit("code_asked", json!({"actor": by, "repo": repo, "session": session, "question": question})); crate::sessions::arrived(); Ok(id) } fn rand_u32() -> u32 { let mut b = [0u8; 4]; if std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut b)).is_err() { return (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos() & 0xffff_ffff) as u32; } u32::from_le_bytes(b) } /// For the runner's poll: the questions not taken yet. Taken once. pub fn take() -> Vec { let mut all = asks(); sweep(&mut all); let mut out = Vec::new(); for (id, a) in all.iter_mut().filter(|(_, a)| a.state == "queued") { a.state = "asked"; a.at = now(); out.push(json!({"id": id, "question": a.question, "repo": a.repo, "session": a.session, "projects": crate::sessions::project_names()})); } out } /// The runner's answer, or why there is none. pub fn answered(id: &str, answer: &str, error: &str) -> Result<()> { let mut all = asks(); let Some(a) = all.get_mut(id) else { bail!("no question {id} (asked too long ago, or before the hub restarted)") }; if error.is_empty() && !answer.trim().is_empty() { a.state = "answered"; a.answer = answer.trim().to_string(); } else { a.state = "failed"; a.answer = if error.is_empty() { "an empty answer".into() } else { error.to_string() }; } drop(all); ASKS.1.notify_all(); Ok(()) } /// Where a question stands, once it is answered or `secs` have passed. pub fn wait(id: &str, secs: u64) -> Result { let until = Instant::now() + Duration::from_secs(secs); let mut all = asks(); loop { sweep(&mut all); let Some(a) = all.get(id) else { bail!("no question {id} (asked too long ago, or before the hub restarted)") }; let left = until.saturating_duration_since(Instant::now()); if matches!(a.state, "answered" | "failed") || left.is_zero() { return Ok(match a.state { "answered" => json!({"state": "answered", "answer": a.answer}), "failed" => json!({"state": "failed", "error": a.answer}), s => json!({"state": s}), }); } // Waked by an answer; and every few seconds, for a question that times out. all = ASKS.1.wait_timeout(all, left.min(Duration::from_secs(5))).unwrap_or_else(|p| p.into_inner()).0; } } // ── The runner's side ─────────────────────────────────────────────────────── /// One question at a time: the worktree it reads is brought to main first. static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); /// Answer a question the poll handed this runner, and tell the hub. pub fn run(job: &Value) { let id = job["id"].as_str().unwrap_or("").to_string(); let started = Instant::now(); let result = (|| -> Result { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|p| p.into_inner()); let home = crate::sessions::sessions_home().context("the runner has no sessions directory (MIDAS_SESSIONS_DIR)")?; let repo = job["repo"].as_str().unwrap_or(""); let own = job["session"].as_str().and_then(crate::sessions::worktree_of).filter(|w| w.join(".git").exists()); let dir = match own { Some(w) => w, None => worktree(&home, repo)?, }; let others: Vec<&str> = job["projects"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); answer(&dir, &framed(job["question"].as_str().unwrap_or(""), repo, &others)) })(); let body = match &result { Ok(a) => json!({"id": id, "answer": a}), Err(e) => json!({"id": id, "error": format!("{e:#}")}), }; eprintln!("question {id}: {} after {:.0} s", if result.is_ok() { "answered" } else { "failed" }, started.elapsed().as_secs_f64()); if let Err(e) = crate::client::post("/v1/hosted/runner/answer", &body) { eprintln!("question {id}: could not give the hub its answer: {e:#}"); } } /// The project's main as it is now, in a worktree of its own: the branch it /// lands on, which for a deck is `presentation` and no `main` at all. pub(crate) fn worktree(home: &Path, repo: &str) -> Result { let checkout = crate::sessions::checkout(home, Some(repo))?; let main = crate::sessions::project_base(repo, "main"); let tip = format!("origin/{main}"); let name = repo.rsplit('/').next().filter(|n| crate::host::name_ok(n)).context("a project with an odd name")?; let work = home.join(format!("ask-{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(&checkout, &["fetch", "-q", "origin", &main])?; if work.join(".git").exists() { git(&work, &["checkout", "-q", "--force", "--detach", &tip])?; } else { // Swept away from under git (the host's sweep of idle worktrees): forget it first. git(&checkout, &["worktree", "prune"])?; git(&checkout, &["worktree", "add", "-q", "--detach", &work.to_string_lossy(), &tip])?; } Ok(work) } /// The question, with which project it is read in and which others the /// workspace has: a reader that knew only its own said "no such thing here" /// of a talk's slides, which live in another project. fn framed(question: &str, repo: &str, projects: &[&str]) -> String { let name = |r: &str| r.rsplit('/').next().unwrap_or(r).to_string(); let others: Vec = projects.iter().filter(|p| **p != repo).map(|p| name(p)).collect(); if others.is_empty() { return question.to_string(); } format!("You are reading the project {}. The workspace's other projects are {}. If what is asked about is not in this one, \ say so and say which of the others most likely holds it, rather than only that it does not exist.\n\n{question}", name(repo), others.join(", ")) } /// Claude Code's answer, read-only, from `dir`. fn answer(dir: &Path, question: &str) -> Result { let model = crate::client::setting("MIDAS_ASK_MODEL").unwrap_or_else(|| MODEL.into()); read_only(dir, question, STYLE, &model, RUN_S) } /// One prompt to Claude Code in `dir`, with only its read, search and list /// tools, and its last words: what the voice's questions and the autopilot's /// decisions (autopilot.rs) are both answered with. pub fn read_only(dir: &Path, prompt: &str, system: &str, model: &str, secs: u64) -> Result { read_only_watched(dir, prompt, system, model, secs, &mut |_| {}) } /// What Claude Code does on its way to an answer, as it does it: a tool it called (its name and input), or what it /// said between them. pub enum Step<'a> { Tool(&'a str, &'a Value), Said(&'a str), } /// `read_only`, telling `on` each step as it comes (Claude Code's `stream-json`): the scout's round shows the /// person what it reads while it reads (tree.rs). pub fn read_only_watched(dir: &Path, prompt: &str, system: &str, model: &str, secs: u64, on: &mut dyn FnMut(Step)) -> Result { let claude = crate::client::setting("MIDAS_CLAUDE").unwrap_or_else(|| "claude".into()); let mut child = Command::new(claude) .args(["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence", "--restricted", "--strict-mcp-config", "--tools", "Read,Grep,Glob"]) .args(["--model", model, "--append-system-prompt", system]) .arg(prompt) .current_dir(dir) // Not a session of the workshop: no node, no hub notes. .env_remove("MIDAS_OWNER") .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()) .spawn().context("starting claude")?; let stdout = child.stdout.take().expect("piped"); let (tx, rx) = std::sync::mpsc::channel::(); let reader = std::thread::spawn(move || { for line in std::io::BufRead::lines(std::io::BufReader::new(stdout)).map_while(Result::ok) { if tx.send(line).is_err() { break; } } }); // The last event is the answer (`"type": "result"`); each before it, a turn of the assistant's, is its steps. let mut v = Value::Null; let mut seen = |line: &str, v: &mut Value| { let Ok(e) = serde_json::from_str::(line) else { return }; if e["type"] == "result" { *v = e; return; } if e["type"] != "assistant" { return; } for c in e["message"]["content"].as_array().into_iter().flatten() { match c["type"].as_str() { Some("tool_use") => on(Step::Tool(c["name"].as_str().unwrap_or(""), &c["input"])), Some("text") => { if let Some(t) = c["text"].as_str().map(str::trim).filter(|t| !t.is_empty()) { on(Step::Said(t)); } } _ => {} } } }; let until = Instant::now() + Duration::from_secs(secs); let status = loop { match rx.recv_timeout(Duration::from_millis(200)) { Ok(line) => seen(&line, &mut v), Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => std::thread::sleep(Duration::from_millis(200)), } if let Some(s) = child.try_wait()? { break s; } if Instant::now() >= until { let _ = child.kill(); let _ = child.wait(); bail!("no answer within {} minutes", secs / 60); } }; // What it wrote before it ended. let _ = reader.join(); for line in rx.try_iter() { seen(&line, &mut v); } let text = v["result"].as_str().unwrap_or("").trim().to_string(); if !status.success() || v["is_error"] == true || text.is_empty() { let mut err = String::new(); if let Some(mut e) = child.stderr.take() { let _ = e.read_to_string(&mut err); } let why = [text.as_str(), err.trim()].into_iter().find(|s| !s.is_empty()).unwrap_or("it said nothing"); bail!("claude: {}", why.chars().take(300).collect::()); } Ok(text) } #[cfg(test)] mod tests { use super::*; fn put(id: &str, state: &'static str, at: i64) { asks().insert(id.into(), Ask { question: "q".into(), repo: "a/b".into(), session: None, state, answer: String::new(), at }); } #[test] fn a_question_is_taken_once_and_waits_for_its_answer() { put("qtest1", "queued", now()); let taken = take(); assert!(taken.iter().any(|j| j["id"] == "qtest1")); assert!(!take().iter().any(|j| j["id"] == "qtest1"), "taken once"); assert_eq!(wait("qtest1", 0).unwrap()["state"], "asked"); answered("qtest1", "It is in hub.rs.", "").unwrap(); assert_eq!(wait("qtest1", 5).unwrap(), json!({"state": "answered", "answer": "It is in hub.rs."})); put("qtest2", "asked", now()); answered("qtest2", "", "claude: no").unwrap(); assert_eq!(wait("qtest2", 0).unwrap()["error"], "claude: no"); } #[test] fn questions_nobody_answers_fail_and_old_ones_go() { put("qtest3", "queued", now() - TAKE_S - 1); put("qtest4", "asked", now() - ANSWER_S - 1); put("qtest5", "answered", now() - KEEP_S - 1); assert_eq!(wait("qtest3", 0).unwrap()["state"], "failed"); assert_eq!(wait("qtest4", 0).unwrap()["state"], "failed"); assert!(wait("qtest5", 0).is_err()); assert!(answered("qnone", "x", "").is_err()); } #[test] fn the_reader_knows_where_else_to_look() { let q = framed("Which slides are there?", "acme/cartopolis", &["acme/cartopolis", "acme/about-cartopolis"]); assert!(q.starts_with("You are reading the project cartopolis. The workspace's other projects are about-cartopolis.")); assert!(q.ends_with("\n\nWhich slides are there?")); assert_eq!(framed("Q?", "a/b", &["a/b"]), "Q?", "nothing to add with one project"); } }