Craft Anything: understand how any software works, and craft your own.
Rust
Explain failed agent runs, keep a log to open, and stop offering git servers as computers (#3)
Brandon Thomas6a120011a1a9
diff --git a/apps/craft-anything-cli/src/ai_cmd.rs b/apps/craft-anything-cli/src/ai_cmd.rsindex 900a9b02..a8161fcf 100644--- a/apps/craft-anything-cli/src/ai_cmd.rs+++ b/apps/craft-anything-cli/src/ai_cmd.rs@@ -132,13 +132,16 @@ pub fn chat(cli: &Cli, a: &ChatArgs) -> u8 {}conv.answer_consent(call_id, cli.allow_run);}- AgentEvent::Error { message, remediation } => {+ AgentEvent::Error { message, remediation, log } => {code = 1;if !jsonl {eprintln!("error: {message}");if let Some(r) = remediation {eprintln!("fix: {r}");}+ if let Some(l) = log {+ eprintln!("log: {}", l.display());+ }}}AgentEvent::TurnDone { backend, input_tokens, output_tokens, cost_usd } => {diff --git a/apps/craft-anything-cli/src/rebuild_cmd.rs b/apps/craft-anything-cli/src/rebuild_cmd.rsindex 8507ce83..0ae5a3b3 100644--- a/apps/craft-anything-cli/src/rebuild_cmd.rs+++ b/apps/craft-anything-cli/src/rebuild_cmd.rs@@ -149,9 +149,15 @@ fn run(cli: &Cli, a: &RebuildArgs) -> Result<bool, ToolError> {end_line(&mut line_open);println!(" · {tool}");}- RunEvent::Agent(AgentEvent::Error { message, .. }) => {+ RunEvent::Agent(AgentEvent::Error { message, remediation, log }) => {end_line(&mut line_open);println!(" ! {message}");+ if let Some(r) = remediation {+ println!("{r}");+ }+ if let Some(l) = log {+ println!(" log: {}", l.display());+ }}RunEvent::Agent(_) => {}RunEvent::Note(text) => {diff --git a/crates/ai/src/agent.rs b/crates/ai/src/agent.rsindex 085d2343..313842ad 100644--- a/crates/ai/src/agent.rs+++ b/crates/ai/src/agent.rs@@ -294,6 +294,7 @@ impl AgentLoop {self.emit(AgentEvent::Error {message: format!("Stopped after {max_turns} steps without a final answer."),remediation: Some("Ask it to continue, or narrow the question.".into()),+ log: None,});break;}@@ -329,6 +330,7 @@ impl AgentLoop {self.emit(AgentEvent::Error {message: "The model declined to answer this request.".into(),remediation: Some("Rephrase the question, say why you're examining the software, or try another backend.".into()),+ log: None,});self.host.journal("error", json!({"kind": "refusal", "backend": slot_name}));// Drop the refused turn so the conversation stays usable.@@ -472,7 +474,7 @@ impl AgentLoop {self.emit(AgentEvent::Status { text: format!("{name} failed ({}). Trying {next}…", e.message) });continue;}- self.emit(AgentEvent::Error { message: format!("{name}: {}", e.message), remediation: e.remediation });+ self.emit(AgentEvent::Error { message: format!("{name}: {}", e.message), remediation: e.remediation, log: None });return None;}}@@ -647,6 +649,7 @@ impl ApiConversation {let _ = etx.send(AgentEvent::Error {message: "The assistant hit a bug and stopped safely.".into(),remediation: Some("Start a new chat.".into()),+ log: None,});}busy2.store(false, Ordering::SeqCst);@@ -667,7 +670,11 @@ impl Conversation for ApiConversation {self.busy.store(true, Ordering::SeqCst);if self.to_worker.send(text.to_string()).is_err() {self.busy.store(false, Ordering::SeqCst);- self.queued.push(AgentEvent::Error { message: "The assistant isn't running any more.".into(), remediation: Some("Start a new chat.".into()) });+ self.queued.push(AgentEvent::Error {+ message: "The assistant isn't running any more.".into(),+ remediation: Some("Start a new chat.".into()),+ log: None,+ });}}diff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rsindex 322110c9..170f9fd8 100644--- a/crates/ai/src/cli_agents/acp.rs+++ b/crates/ai/src/cli_agents/acp.rs@@ -181,7 +181,7 @@ impl AcpCore {fn fail(&mut self, message: String, remediation: Option<String>) -> Vec<Out> {self.queued.clear();- vec![Out::Event(AgentEvent::Error { message, remediation }), self.turn_done(), Out::TurnEnded]+ vec![Out::Event(AgentEvent::Error { message, remediation, log: None }), self.turn_done(), Out::TurnEnded]}fn turn_done(&self) -> Out {@@ -413,9 +413,16 @@ pub struct AcpConversation {busy: Arc<AtomicBool>,approver: Option<Approver>,preamble: String,+ logs: Option<PathBuf>,}impl AcpConversation {+ /// Where to write a log if the agent stops unexpectedly ([`crate::failure_log`]).+ pub fn with_logs(mut self, logs: Option<PathBuf>) -> Self {+ self.logs = logs;+ self+ }+/// Text put before each message, as the CLI runs do (who it works for, how to use our tools).pub fn with_preamble(mut self, preamble: String) -> Self {self.preamble = preamble;@@ -447,6 +454,7 @@ impl AcpConversation {busy: Arc::default(),approver: None,preamble: String::new(),+ logs: None,}}@@ -518,6 +526,7 @@ impl Conversation for AcpConversation {let _ = self.tx.send(AgentEvent::Error {message: "Still working on the last message.".into(),remediation: Some("Wait for it to finish or press stop.".into()),+ log: None,});return;}@@ -526,7 +535,7 @@ impl Conversation for AcpConversation {let _ = self.tx.send(AgentEvent::Status { text: format!("Starting {}…", display_for(&self.agent)) });if let Err(e) = self.spawn() {self.busy.store(false, Ordering::SeqCst);- let _ = self.tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation });+ let _ = self.tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation, log: None });let _ = self.tx.send(AgentEvent::TurnDone { backend: self.backend.clone(), input_tokens: 0, output_tokens: 0, cost_usd: None });return;}@@ -546,9 +555,27 @@ impl Conversation for AcpConversation {self.busy.store(false, Ordering::SeqCst);let tail = self.lock().as_ref().map(|s| s.stderr.iter().cloned().collect::<Vec<_>>().join("\n")).unwrap_or_default();events.extend(self.rx.try_iter());+ let command = craft_anything_platform::process::printable_command(std::ffi::OsStr::new(&self.program), &self.args);+ let check = format!("{} --version", crate::ssh::shell_quote(&self.program));+ let log = self.logs.as_ref().and_then(|dir| {+ let report = crate::failure_log::Report {+ what: format!("{} ({})", display_for(&self.agent), self.backend),+ command: command.clone(),+ check: check.clone(),+ error: Some("It stopped in the middle of a message.".into()),+ cwd: Some(self.cwd.clone()),+ stderr: tail.clone().into_bytes(),+ ..Default::default()+ };+ crate::failure_log::write(dir, &report).map_err(|e| log::warn!("couldn't write a failure log: {e}")).ok()+ });events.push(AgentEvent::Error {message: format!("{} stopped unexpectedly.{}", display_for(&self.agent), if tail.is_empty() { String::new() } else { format!("\n{tail}") }),- remediation: Some(format!("Check that {} is installed and signed in: run it once in a terminal.", display_for(&self.agent))),+ remediation: Some(format!(+ "Check that {} is installed and signed in. To test it, run:\n{check}\n\nWhat ran:\n{command}",+ display_for(&self.agent)+ )),+ log,});events.push(AgentEvent::TurnDone { backend: self.backend.clone(), input_tokens: 0, output_tokens: 0, cost_usd: None });}@@ -663,7 +690,7 @@ mod tests {c.prompt("hi");let outs = c.line(r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"Authentication required"}}"#);assert!(outs.contains(&Out::TurnEnded));- assert!(matches!(&events(outs)[0], AgentEvent::Error { message, remediation: Some(_) } if message.contains("Authentication required")));+ assert!(matches!(&events(outs)[0], AgentEvent::Error { message, remediation: Some(_), .. } if message.contains("Authentication required")));let refused = sent(&c.line(r#"{"jsonrpc":"2.0","id":9,"method":"fs/read_text_file","params":{"path":"/etc/passwd"}}"#));assert_eq!(refused[0]["error"]["code"], -32601);assert!(c.line("not json").is_empty());diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rsindex 1d4a1c18..b4dd10fd 100644--- a/crates/ai/src/cli_agents/adapters.rs+++ b/crates/ai/src/cli_agents/adapters.rs@@ -251,7 +251,7 @@ impl AgentAdapter for ClaudeCode {}if v.get("is_error").and_then(Value::as_bool).unwrap_or(false) {let why = if s("result").is_empty() { s("subtype") } else { s("result") };- out.push(AgentEvent::Error { message: format!("Claude Code stopped: {why}"), remediation: sign_in_hint(&why) });+ out.push(AgentEvent::Error { message: format!("Claude Code stopped: {why}"), remediation: sign_in_hint(&why), log: None });}}_ => {}@@ -346,7 +346,7 @@ impl AgentAdapter for Codex {}("turn.failed", _) | ("error", _) => {let m = v.pointer("/error/message").or_else(|| v.get("message")).and_then(Value::as_str).unwrap_or("unknown error");- out.push(AgentEvent::Error { message: format!("Codex: {m}"), remediation: None });+ out.push(AgentEvent::Error { message: format!("Codex: {m}"), remediation: None, log: None });}_ => {}}@@ -392,7 +392,7 @@ impl AgentAdapter for GeminiCli {let text = v.get("output").map(content_text).unwrap_or_default();out.push(p.finished(&id, ok, &text));}- "error" => out.push(AgentEvent::Error { message: format!("Gemini CLI: {}", s("message")), remediation: None }),+ "error" => out.push(AgentEvent::Error { message: format!("Gemini CLI: {}", s("message")), remediation: None, log: None }),"result" => {p.saw_result = true;if let Some(st) = v.get("stats") {diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex f4ce8122..1d44be7f 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -16,9 +16,11 @@ pub use adapters::{AgentAdapter, AgentAdapters, ArgsCx};use crate::config::BackendOptions;use crate::model::Stop;use crate::{AgentEvent, BackendConfig, Conversation};+use craft_anything_evidence::ToolError;use craft_anything_platform::process::Process;use serde_json::{Value, json};use std::collections::HashMap;+use std::ffi::OsStr;use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::mpsc::{Receiver, Sender};@@ -273,6 +275,8 @@ pub struct CliSpec {/// builder's own session is never changed. Only adapters that/// [answer questions](adapters::AgentAdapter::answers_questions) take it.pub question: bool,+ /// Where a failed run writes what's known about it ([`crate::failure_log`]). None writes no log.+ pub logs: Option<PathBuf>,}/// What a building run needs besides the working folder.@@ -309,6 +313,7 @@ impl CliSpec {resume: None,deep: false,preamble: None,+ logs: None,adapters: AgentAdapters::built_in(),question: false,}@@ -346,7 +351,7 @@ fn acp_for(spec: &CliSpec) -> Option<AcpConversation> {let cwd = spec.project.clone().or_else(|| std::env::current_dir().ok()).unwrap_or_else(std::env::temp_dir);let mcp = mcp_for(spec, false);let preamble = spec.preamble.clone().unwrap_or_else(|| crate::prompt::cli_preamble(spec.beginner));- Some(AcpConversation::new(&spec.config.name, &agent, program, args, cwd, mcp, spec.resume.clone()).with_preamble(preamble))+ Some(AcpConversation::new(&spec.config.name, &agent, program, args, cwd, mcp, spec.resume.clone()).with_preamble(preamble).with_logs(spec.logs.clone()))}/// A conversation backed by an agent CLI. Each message is one CLI run; Claude Code runs resume@@ -405,6 +410,7 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, seslet _ = tx.send(AgentEvent::Error {message: format!("{name} can't be kept to only reading here, so it isn't asked questions about a build."),remediation: Some("Ask with Claude Code, or with an AI that has an API key.".into()),+ log: None,});return;}@@ -416,6 +422,7 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, ses(None, _, false) => Access::Analyse,};let args = build_args(adapter.as_ref(), &spec.options, text, &preamble, &mcp, if adapter.resumes() { resume.as_deref() } else { None }, access);+ let shown = FailureContext::new(&program, &args, text, remote.as_deref(), spec);let (prog, argv) = match &remote {Some(host) => {let mut remote_cmd = vec![program.clone()];@@ -467,20 +474,141 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, ses}match result {Ok(out) if !out.success && !p.saw_result => {- let e = craft_anything_platform::process::nonzero_error(&display_for(&agent), &out);- let _ = tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation });+ let _ = tx.send(shown.exit_event(&agent, &out));+ }+ Ok(out) if !out.success => {+ // The agent already said what went wrong; keep the rest for anyone looking into it.+ if let Some(path) = shown.save(&agent, Some(&out), None).0 {+ let _ = tx.send(AgentEvent::Status { text: format!("The details are in {}", path.display()) });+ }}Ok(_) => {}Err(e) if e.code == craft_anything_evidence::ErrorCode::Cancelled => {let _ = tx.send(AgentEvent::Status { text: "Stopped.".into() });}Err(e) => {- let _ = tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation });+ let _ = tx.send(shown.error_event(&agent, e));}}let _ = tx.send(AgentEvent::TurnDone { backend: name, input_tokens: p.input_tokens, output_tokens: p.output_tokens, cost_usd: p.cost_usd });}+/// What's needed to explain a failed CLI run: the command with the person's message left out, and+/// where to write the log.+struct FailureContext {+ command: String,+ check: String,+ program: String,+ host: Option<String>,+ backend: String,+ cwd: Option<PathBuf>,+ logs: Option<PathBuf>,+}++impl FailureContext {+ fn new(program: &str, args: &[String], message: &str, host: Option<&str>, spec: &CliSpec) -> Self {+ use craft_anything_platform::process::printable_command;+ let message = message.trim();+ let args: Vec<String> = args+ .iter()+ .map(|a| if !message.is_empty() && a.contains(message) { format!("[your message, {} characters]", message.chars().count()) } else { a.clone() })+ .collect();+ let local = printable_command(OsStr::new(program), &args);+ let (command, check) = match host {+ Some(h) => {+ let options = crate::ssh::SSH_OPTIONS.join(" ");+ (format!("ssh {options} -T {} -- {local}", crate::ssh::shell_quote(h)), crate::ssh::check_command(h, program))+ }+ None => (local, format!("{} --version", crate::ssh::shell_quote(program))),+ };+ FailureContext {+ command,+ check,+ program: program.to_string(),+ host: host.map(str::to_string),+ backend: spec.config.name.clone(),+ cwd: spec.project.clone().filter(|_| host.is_none()),+ logs: spec.logs.clone(),+ }+ }++ /// Why this run failed, when it was ssh (or the remote computer) that says so.+ fn ssh_failure(&self, out: &craft_anything_platform::Output) -> Option<crate::ssh::SshFailure> {+ let host = self.host.as_deref()?;+ crate::ssh::diagnose(host, &self.program, crate::ssh::is_git_server(host), out.code, &out.stderr_text())+ }++ /// Write the log. Returns its path, or what to tell the person when it couldn't be written.+ fn save(&self, agent: &str, out: Option<&craft_anything_platform::Output>, diagnosis: Option<&str>) -> (Option<PathBuf>, Option<String>) {+ self.save_with(agent, out, diagnosis, None)+ }++ fn save_with(+ &self,+ agent: &str,+ out: Option<&craft_anything_platform::Output>,+ diagnosis: Option<&str>,+ error: Option<&str>,+ ) -> (Option<PathBuf>, Option<String>) {+ let Some(dir) = &self.logs else { return (None, None) };+ let report = crate::failure_log::Report {+ what: format!("{} ({})", display_for(agent), self.backend),+ command: self.command.clone(),+ check: self.check.clone(),+ diagnosis: diagnosis.map(str::to_string),+ error: error.map(str::to_string),+ cwd: self.cwd.clone(),+ exit_code: out.and_then(|o| o.code),+ duration: out.map(|o| o.duration),+ stdout: out.map(|o| o.stdout.clone()).unwrap_or_default(),+ stderr: out.map(|o| o.stderr.clone()).unwrap_or_default(),+ };+ match crate::failure_log::write(dir, &report) {+ Ok(path) => {+ log::warn!("{} failed; details in {}", display_for(agent), path.display());+ (Some(path), None)+ }+ Err(e) => {+ log::warn!("couldn't write a failure log: {e}");+ (None, Some(format!("The details couldn't be saved: {e}")))+ }+ }+ }++ fn exit_event(&self, agent: &str, out: &craft_anything_platform::Output) -> AgentEvent {+ let name = display_for(agent);+ let plain = craft_anything_platform::process::nonzero_error_with(&name, out, Some(&self.command));+ let excerpt = craft_anything_platform::process::output_excerpt(&String::from_utf8_lossy(if out.stderr.is_empty() { &out.stdout } else { &out.stderr }));+ let (message, mut remediation) = match self.ssh_failure(out) {+ Some(f) => {+ let host = self.host.as_deref().unwrap_or_default();+ let said = if excerpt.is_empty() { String::new() } else { format!("\n\nssh printed:\n{excerpt}") };+ (format!("Couldn't run {name} on {host}: {}.", f.what), format!("{}{said}\n\nTo test it yourself, run:\n{}", f.fix, self.check))+ }+ None => (plain.message, plain.remediation.unwrap_or_default()),+ };+ let (log, unsaved) = self.save(agent, Some(out), Some(&message));+ if let Some(u) = unsaved {+ remediation.push_str(&format!("\n\n{u}"));+ }+ AgentEvent::Error { message, remediation: Some(remediation), log }+ }++ fn error_event(&self, agent: &str, e: ToolError) -> AgentEvent {+ let details = e.details.as_ref().map(ToString::to_string);+ let text = match details {+ Some(d) => format!("{}\n{d}", e.message),+ None => e.message.clone(),+ };+ let (log, unsaved) = self.save_with(agent, None, None, Some(&text));+ let remediation = match (e.remediation, unsaved) {+ (Some(r), Some(u)) => Some(format!("{r}\n\n{u}")),+ (r, u) => r.or(u),+ };+ AgentEvent::Error { message: e.message, remediation, log }+ }+}+impl Conversation for CliConversation {fn session_id(&self) -> Option<String> {CliConversation::session_id(self)@@ -491,6 +619,7 @@ impl Conversation for CliConversation {let _ = self.tx.send(AgentEvent::Error {message: "Still working on the last message.".into(),remediation: Some("Wait for it to finish or press stop.".into()),+ log: None,});return;}@@ -501,14 +630,14 @@ impl Conversation for CliConversation {let spawned = std::thread::Builder::new().name("ai-cli".into()).spawn(move || {let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_cli(&spec, &text, &tx, &stop, &session, &verified)));if r.is_err() {- let _ = tx.send(AgentEvent::Error { message: "The agent runner hit a bug and stopped safely.".into(), remediation: None });+ let _ = tx.send(AgentEvent::Error { message: "The agent runner hit a bug and stopped safely.".into(), remediation: None, log: None });let _ = tx.send(AgentEvent::TurnDone { backend: spec.config.name.clone(), input_tokens: 0, output_tokens: 0, cost_usd: None });}busy.store(false, Ordering::SeqCst);});if spawned.is_err() {self.busy.store(false, Ordering::SeqCst);- let _ = self.tx.send(AgentEvent::Error { message: "Couldn't start a worker thread.".into(), remediation: None });+ let _ = self.tx.send(AgentEvent::Error { message: "Couldn't start a worker thread.".into(), remediation: None, log: None });}}@@ -595,12 +724,77 @@ mod tests {assert_eq!(dropped, ["CLAUDECODE", "CLAUDE_AGENT_SDK_VERSION", "CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH", "CLAUDE_CODE_SESSION_ID"]);}+ fn failed(code: i32, stderr: &str) -> craft_anything_platform::Output {+ craft_anything_platform::Output {+ code: Some(code),+ success: false,+ stdout: Vec::new(),+ stderr: stderr.as_bytes().to_vec(),+ stdout_truncated: false,+ stderr_truncated: false,+ duration: Duration::from_millis(400),+ }+ }++ fn context(host: Option<&str>, logs: Option<PathBuf>) -> FailureContext {+ let config = BackendConfig {+ name: "Mine".into(),+ kind: BackendKind::AgentCli,+ model: "claude-code".into(),+ base_url: None,+ ssh_host: host.map(str::to_string),+ enabled: true,+ };+ let spec = CliSpec { logs, ..CliSpec::new(config, BackendOptions::default(), false, None) };+ let args = ["-p".to_string(), "PRE private plans for my app".to_string(), "--verbose".to_string()];+ FailureContext::new("claude", &args, "private plans for my app", host, &spec)+ }++ #[test]+ fn a_failed_ssh_run_says_what_happened_and_saves_a_log() {+ let dir = tempfile::tempdir().unwrap();+ let ev = context(Some("github.com"), Some(dir.path().to_path_buf())).exit_event("claude-code", &failed(255, "exec request failed on channel 0\n"));+ let AgentEvent::Error { message, remediation, log } = ev else { panic!("not an error") };+ let help = remediation.unwrap();+ assert!(message.contains("Couldn't run Claude Code on github.com: github.com is a git server"), "{message}");+ assert!(help.contains("exec request failed on channel 0") && help.contains("ssh -o BatchMode=yes -T github.com -- claude --version"), "{help}");+ assert!(!help.contains("by hand") && !help.contains("below"), "{help}");+ let text = std::fs::read_to_string(log.unwrap()).unwrap();+ for part in ["Exit code: 255", "exec request failed on channel 0", "git server", "claude --version", "--verbose", "[your message, 24 characters]"] {+ assert!(text.contains(part), "{part} is missing from:\n{text}");+ }+ assert!(!text.contains("private plans"), "the message stays out of the log:\n{text}");+ }++ #[test]+ fn a_failed_local_run_shows_its_output_and_command() {+ let dir = tempfile::tempdir().unwrap();+ let ev = context(None, Some(dir.path().to_path_buf())).exit_event("claude-code", &failed(3, "first\nreal reason\n"));+ let AgentEvent::Error { message, remediation, log } = ev else { panic!("not an error") };+ let help = remediation.unwrap();+ assert!(message.contains("exit code 3: real reason"), "{message}");+ assert!(help.contains("first\nreal reason") && help.contains("claude -p '[your message, 24 characters]' --verbose"), "{help}");+ assert!(log.is_some());+ }++ #[test]+ fn without_a_log_folder_nothing_is_written_and_a_failed_write_is_reported() {+ let ev = context(None, None).exit_event("claude-code", &failed(1, "x"));+ assert!(matches!(ev, AgentEvent::Error { log: None, .. }));+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("a-file");+ std::fs::write(&file, "").unwrap();+ let AgentEvent::Error { remediation, log, .. } = context(None, Some(file)).exit_event("claude-code", &failed(1, "x")) else { panic!("not an error") };+ assert!(log.is_none());+ assert!(remediation.unwrap().contains("The details couldn't be saved"));+ }+#[test]fn sign_in_failures_get_a_plain_fix() {let mut p = StreamParser::new(adapter_for("claude-code"));let ev = p.line(&json!({"type":"result","subtype":"success","is_error":true,"result":"Failed to authenticate: OAuth session expired"}).to_string());match &ev[0] {- AgentEvent::Error { message, remediation } => {+ AgentEvent::Error { message, remediation, .. } => {assert_eq!(message, "Claude Code stopped: Failed to authenticate: OAuth session expired");assert!(remediation.as_deref().unwrap_or_default().contains("claude auth login"));}diff --git a/crates/ai/src/failure_log.rs b/crates/ai/src/failure_log.rsnew file mode 100644index 00000000..513dee82--- /dev/null+++ b/crates/ai/src/failure_log.rs@@ -0,0 +1,153 @@+//! Logs of failed runs, one file each, to open and inspect when something goes wrong: what ran,+//! what it printed, and what we made of it. They stay on this computer, readable only by its+//! owner. The person's message is never written, and secret-looking flags are masked+//! ([`craft_anything_platform::process::printable_command`]).++use craft_anything_evidence::{ErrorCode, ToolError};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Duration;++/// Logs kept; the oldest go first.+const KEEP: usize = 50;+/// The most of each output stream kept in a log.+const MAX_STREAM_BYTES: usize = 256 * 1024;++static COUNTER: AtomicU64 = AtomicU64::new(0);++/// The folder for failure logs inside a config folder.+pub fn dir_in(config_dir: &Path) -> PathBuf {+ config_dir.join("logs")+}++/// Everything known about a failed run.+#[derive(Debug, Clone, Default)]+pub struct Report {+ /// What failed, in words.+ pub what: String,+ /// What ran, with the person's message left out.+ pub command: String,+ /// A command that tests the program without a message.+ pub check: String,+ /// What we made of it.+ pub diagnosis: Option<String>,+ /// The error, when the program didn't run to an exit code.+ pub error: Option<String>,+ pub cwd: Option<PathBuf>,+ pub exit_code: Option<i32>,+ pub duration: Option<Duration>,+ pub stdout: Vec<u8>,+ pub stderr: Vec<u8>,+}++fn stream(name: &str, bytes: &[u8]) -> String {+ if bytes.is_empty() {+ return format!("--- {name}: empty ---\n");+ }+ let start = bytes.len().saturating_sub(MAX_STREAM_BYTES);+ let kept = String::from_utf8_lossy(bytes.get(start..).unwrap_or_default());+ let note = if start > 0 { format!(" (the last {} of {} bytes)", bytes.len() - start, bytes.len()) } else { String::new() };+ format!("--- {name}{note} ---\n{kept}\n")+}++fn render(r: &Report, date: &str, time: &str) -> String {+ let mut s = format!("Craft Anything {} failure log\nWhen: {date} {time} UTC\nWhat: {}\n", env!("CARGO_PKG_VERSION"), r.what);+ if let Some(d) = &r.diagnosis {+ s.push_str(&format!("Diagnosis: {d}\n"));+ }+ if let Some(e) = &r.error {+ s.push_str(&format!("Error: {e}\n"));+ }+ if let Some(c) = r.exit_code {+ s.push_str(&format!("Exit code: {c}\n"));+ }+ if let Some(d) = r.duration {+ s.push_str(&format!("Ran for: {:.1} s\n", d.as_secs_f64()));+ }+ if let Some(c) = &r.cwd {+ s.push_str(&format!("Working folder: {}\n", c.display()));+ }+ s.push_str(&format!("\nTo test the program:\n{}\n\nWhat ran (the message is left out):\n{}\n\n", r.check, r.command));+ s.push_str(&stream("stderr", &r.stderr));+ s.push('\n');+ s.push_str(&stream("stdout", &r.stdout));+ s+}++/// Write a log into `dir`, creating it, and return its path. Removes the oldest beyond [`KEEP`].+pub fn write(dir: &Path, report: &Report) -> Result<PathBuf, ToolError> {+ std::fs::create_dir_all(dir).map_err(|e| ToolError::new(ErrorCode::FileError, format!("Couldn't create the log folder {}: {e}", dir.display())))?;+ let (_, date, time) = craft_anything_engine::journal::now_utc();+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);+ let name = format!("agent-{date}-{}-{}-{n}.log", time.replace(':', ""), std::process::id());+ let path = dir.join(name);+ craft_anything_platform::write_atomic_private(&path, render(report, &date, &time).as_bytes())?;+ prune(dir, KEEP);+ Ok(path)+}++/// Failing to tidy up never fails the run; the next write tries again.+fn prune(dir: &Path, keep: usize) {+ let Ok(rd) = std::fs::read_dir(dir) else { return };+ let mut logs: Vec<PathBuf> = rd+ .flatten()+ .map(|e| e.path())+ .filter(|p| p.extension().is_some_and(|x| x == "log") && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("agent-")))+ .collect();+ // Names start with the date and time, so they sort oldest first.+ logs.sort();+ for old in logs.iter().take(logs.len().saturating_sub(keep)) {+ if let Err(e) = std::fs::remove_file(old) {+ log::warn!("couldn't remove the old log {}: {e}", old.display());+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_log_holds_what_is_known_and_is_private() {+ let dir = tempfile::tempdir().unwrap();+ let report = Report {+ what: "X".into(),+ command: "x --go".into(),+ check: "x --version".into(),+ exit_code: Some(2),+ stderr: b"boom".to_vec(),+ ..Default::default()+ };+ let path = write(&dir.path().join("logs"), &report).unwrap();+ let text = std::fs::read_to_string(&path).unwrap();+ for part in ["What: X", "Exit code: 2", "x --go", "x --version", "boom", "--- stdout: empty ---"] {+ assert!(text.contains(part), "{part}: {text}");+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);+ }+ }++ #[test]+ fn long_output_keeps_its_end_and_says_so() {+ let mut out = vec![b'a'; MAX_STREAM_BYTES + 10];+ out.extend_from_slice(b"the end");+ let s = stream("stderr", &out);+ assert!(s.ends_with("the end\n") && s.contains("the last") && s.len() < MAX_STREAM_BYTES + 100);+ }++ #[test]+ fn old_logs_are_removed_and_other_files_left_alone() {+ let dir = tempfile::tempdir().unwrap();+ for i in 0..5 {+ std::fs::write(dir.path().join(format!("agent-2026-01-0{i}.log")), "").unwrap();+ }+ std::fs::write(dir.path().join("notes.log"), "").unwrap();+ prune(dir.path(), 2);+ let mut left: Vec<String> = std::fs::read_dir(dir.path()).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();+ left.sort();+ assert_eq!(left, ["agent-2026-01-03.log", "agent-2026-01-04.log", "notes.log"]);+ }+}diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex 451ecb2c..753db950 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -12,6 +12,7 @@ pub mod cli_agents;pub mod config;pub mod context;pub mod detect;+pub mod failure_log;pub mod http;pub mod key_tools;pub mod keys;@@ -172,6 +173,8 @@ pub enum AgentEvent {Error {message: String,remediation: Option<String>,+ /// A log with everything known about the failure, to open and inspect.+ log: Option<std::path::PathBuf>,},}@@ -460,7 +463,11 @@ impl AiHub {};if first.config.kind == BackendKind::AgentCli {let spec = cli_agents::CliSpec::new(first.config.clone(), first.options.clone(), beginner, self.project_root());- return Ok(cli_agents::conversation(cli_agents::CliSpec { deep: !self.engine.session().clean_room(), ..spec }));+ let (deep, logs) = {+ let session = self.engine.session();+ (!session.clean_room(), failure_log::dir_in(&session.config_dir()))+ };+ return Ok(cli_agents::conversation(cli_agents::CliSpec { deep, logs: Some(logs), ..spec }));}let mut chain = vec![self.build_model(&first)?];for name in cfg.chain_from(&first.config.name).into_iter().skip(1) {diff --git a/crates/ai/src/rebuild/feed.rs b/crates/ai/src/rebuild/feed.rsindex fb580595..9b2a9e6a 100644--- a/crates/ai/src/rebuild/feed.rs+++ b/crates/ai/src/rebuild/feed.rs@@ -52,9 +52,9 @@ pub fn apply(feed: &mut Vec<FeedItem>, e: &RunEvent) {Some(FeedItem::Work { notes, .. }) => notes.push(text.clone()),_ => feed.push(FeedItem::Work { tools: Vec::new(), notes: vec![text.clone()] }),},- RunEvent::Agent(AgentEvent::Error { message, remediation }) => {+ RunEvent::Agent(AgentEvent::Error { message, remediation, log }) => {end_stream(feed);- feed.push(FeedItem::Error { message: message.clone(), remediation: remediation.clone() });+ feed.push(FeedItem::Error { message: message.clone(), remediation: remediation.clone(), log: log.clone() });}RunEvent::Agent(_) => end_stream(feed),RunEvent::Note(shown) => {@@ -71,7 +71,7 @@ pub fn apply(feed: &mut Vec<FeedItem>, e: &RunEvent) {if *paused {feed.push(FeedItem::Paused);} else if !ok && !explained {- feed.push(FeedItem::Error { message: message.clone(), remediation: None });+ feed.push(FeedItem::Error { message: message.clone(), remediation: None, log: None });}}}diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rsindex 4e1aa8a2..7ede6a67 100644--- a/crates/ai/src/rebuild/mod.rs+++ b/crates/ai/src/rebuild/mod.rs@@ -508,6 +508,29 @@ impl Worker {}}+ /// How the builder's agent runs. Reads the session once: a lock taken twice in one statement+ /// is held by the first until the statement ends, and the second then waits forever.+ fn agent_spec(&self, ws: &Workspace, entry: &crate::BackendEntry, opts: &RunOptions) -> CliSpec {+ let (deep, config_dir) = {+ let session = self.engine.session();+ (!session.clean_room(), session.config_dir())+ };+ CliSpec {+ builder: Some(Builder { investigation: Some(ws.investigation_dir()), inbox: ws.inbox_dir() }),+ deep,+ logs: Some(crate::failure_log::dir_in(&config_dir)),+ resume: ws.manifest.agent_session.clone(),+ preamble: Some(+ "You work inside Craft Anything for a person who doesn't code. The message below is your task.++"+ .into(),+ ),+ adapters: opts.adapters.clone(),+ ..CliSpec::new(entry.config.clone(), entry.options.clone(), opts.beginner, Some(ws.root.clone()))+ }+ }+fn run(&mut self,ws: &mut Workspace,@@ -555,19 +578,7 @@ impl Worker {let api_loop = api.is_some();// A coding agent that never saved a session starts over, so it needs the brief.let has_history = resumable && (api_loop || ws.manifest.agent_session.is_some());- let spec = CliSpec {- builder: Some(Builder { investigation: Some(ws.investigation_dir()), inbox: ws.inbox_dir() }),- deep: !self.engine.session().clean_room(),- resume: ws.manifest.agent_session.clone(),- preamble: Some(- "You work inside Craft Anything for a person who doesn't code. The message below is your task.--"- .into(),- ),- adapters: opts.adapters.clone(),- ..CliSpec::new(entry.config.clone(), entry.options.clone(), opts.beginner, Some(ws.root.clone()))- };+ let spec = self.agent_spec(ws, &entry, opts);let mut agent: Box<dyn Conversation> = match api {Some(a) => Box::new(a),None => crate::cli_agents::builder_conversation(spec, self.approver(ws)),@@ -751,7 +762,7 @@ impl Worker {{self.decompiled = true}- AgentEvent::Error { message, remediation } => failed = Some((message.clone(), remediation.clone())),+ AgentEvent::Error { message, remediation, .. } => failed = Some((message.clone(), remediation.clone())),_ => {}}if let AgentEvent::TurnDone { input_tokens, output_tokens, cost_usd, .. } = &e {diff --git a/crates/ai/src/rebuild/question.rs b/crates/ai/src/rebuild/question.rsindex d3ef054b..7700097f 100644--- a/crates/ai/src/rebuild/question.rs+++ b/crates/ai/src/rebuild/question.rs@@ -56,7 +56,14 @@ pub struct Answered {/// the caller, which may hold the session: a tool does while it runs, so locking it here would/// wait forever). Blocks until it's answered, `cancel` is set, or [`WAIT`] passes: call it off/// the UI thread.-pub fn ask(hub: &AiHub, settings: &craft_anything_engine::Settings, ws: &Workspace, question: &str, cancel: &CancelToken) -> Result<Answered, ToolError> {+pub fn ask(+ hub: &AiHub,+ settings: &craft_anything_engine::Settings,+ logs: Option<std::path::PathBuf>,+ ws: &Workspace,+ question: &str,+ cancel: &CancelToken,+) -> Result<Answered, ToolError> {let question = question.trim();if question.is_empty() || question.len() > MAX_QUESTION {return Err(ToolError::invalid(format!("A question is 1 to {MAX_QUESTION} characters.")));@@ -71,6 +78,7 @@ pub fn ask(hub: &AiHub, settings: &craft_anything_engine::Settings, ws: &Workspalet spec = CliSpec {question: true,deep,+ logs,resume: session,preamble: Some(PREAMBLE.into()),..CliSpec::new(entry.config.clone(), entry.options.clone(), false, Some(ws.root.clone()))@@ -111,7 +119,7 @@ fn collect(conv: &mut dyn Conversation, cancel: &CancelToken, wait: Duration) ->match e {AgentEvent::TextDelta { text: t } => text.push_str(&t),AgentEvent::TurnDone { cost_usd, .. } => return Ok((text.trim().to_string(), cost_usd)),- AgentEvent::Error { message, remediation } => {+ AgentEvent::Error { message, remediation, .. } => {let e = ToolError::new(ErrorCode::ProgramFailed, message);return Err(match remediation {Some(r) => e.with_remediation(r),@@ -242,7 +250,7 @@ mod tests {let done = AgentEvent::TurnDone { backend: "A".into(), input_tokens: 1, output_tokens: 1, cost_usd: Some(0.02) };let mut ok = Scripted(vec![words("They're in "), words("app/src."), done]);assert_eq!(collect(&mut ok, &CancelToken::default(), WAIT).unwrap(), ("They're in app/src.".to_string(), Some(0.02)));- let mut bad = Scripted(vec![AgentEvent::Error { message: "not signed in".into(), remediation: Some("Sign in".into()) }]);+ let mut bad = Scripted(vec![AgentEvent::Error { message: "not signed in".into(), remediation: Some("Sign in".into()), log: None }]);let e = collect(&mut bad, &CancelToken::default(), WAIT).unwrap_err();assert_eq!((e.message.as_str(), e.remediation.as_deref()), ("not signed in", Some("Sign in")));let mut slow = Scripted(Vec::new());diff --git a/crates/ai/src/rebuild/tests.rs b/crates/ai/src/rebuild/tests.rsindex a2f50c8e..4e16c1de 100644--- a/crates/ai/src/rebuild/tests.rs+++ b/crates/ai/src/rebuild/tests.rs@@ -1133,6 +1133,46 @@ impl Conversation for ChecksItsWork {}}+#[test]+fn preparing_the_builders_agent_does_not_lock_up() {+ let d = tempfile::tempdir().unwrap();+ let ws = Workspace::create(d.path(), "Arena", "Recreate this game", TargetRef::None).unwrap();+ let (tx, _rx) = std::sync::mpsc::channel();+ let w = Worker {+ wake: Default::default(),+ engine: Arc::new(Engine::new(craft_anything_engine::testing::session())),+ tx,+ stop: CancelToken::default(),+ preview: Arc::default(),+ seen: HashSet::new(),+ inbox: Inbox::new(ws.inbox_dir()),+ editor: None,+ notes: Arc::default(),+ feed: Arc::new(Mutex::new(feed::FeedLog::open(&ws))),+ assets: false,+ decompiled: false,+ usage: None,+ self_check: None,+ };+ let entry = crate::BackendEntry {+ config: crate::BackendConfig {+ name: "x".into(),+ kind: crate::BackendKind::AgentCli,+ model: "claude-code".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ },+ options: Default::default(),+ };+ let (done, finished) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let _ = done.send(w.agent_spec(&ws, &entry, &RunOptions::default()).logs);+ });+ let logs = finished.recv_timeout(std::time::Duration::from_secs(20)).expect("it took the session lock twice and waited on itself");+ assert!(logs.is_some());+}+#[test]fn the_run_answers_the_builders_own_check_during_its_turn() {let d = tempfile::tempdir().unwrap();diff --git a/crates/ai/src/rebuild/tools.rs b/crates/ai/src/rebuild/tools.rsindex b1e74a99..8d5b38e6 100644--- a/crates/ai/src/rebuild/tools.rs+++ b/crates/ai/src/rebuild/tools.rs@@ -254,7 +254,8 @@ fn rebuild_question_ask(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,// The session is this call's while it runs: the question gets its settings from here.let mut settings = ctx.session.settings.clone();settings.deep_mode = !ctx.session.clean_room();- let answered = super::question::ask(&AiHub::new(engine), &settings, &ws, &p.question, &ctx.cancel)?;+ let answered =+ super::question::ask(&AiHub::new(engine), &settings, Some(crate::failure_log::dir_in(&ctx.session.config_dir())), &ws, &p.question, &ctx.cancel)?;let question = p.question.trim();let from_session = answered.from == super::question::AnsweredFrom::BuildersSession;let asked = AskedQuestion::new(question.to_string(), answered.answer.clone(), from_session, answered.backend.clone(), answered.cost_usd, after);diff --git a/crates/ai/src/ssh.rs b/crates/ai/src/ssh.rsindex 086d91fe..5c0d5471 100644--- a/crates/ai/src/ssh.rs+++ b/crates/ai/src/ssh.rs@@ -31,12 +31,78 @@ fn ssh_dir() -> Option<PathBuf> {/// Host aliases from `~/.ssh/config` (and files it includes), without wildcard patterns.pub fn ssh_hosts() -> Vec<String> {match ssh_dir() {- Some(d) => hosts_from_file(&d.join("config"), &d, 0),+ Some(d) => hosts_from_file(&d.join("config"), &d, 0, parse_hosts),None => Vec::new(),}}-fn hosts_from_file(path: &Path, base: &Path, depth: u32) -> Vec<String> {+/// `host` is a git server, by its name or by what `~/.ssh/config` says about it. An AI saved before+/// such hosts stopped being offered can still be set to one.+pub fn is_git_server(host: &str) -> bool {+ is_git_host(host) || ssh_dir().is_some_and(|d| hosts_from_file(&d.join("config"), &d, 0, git_aliases).iter().any(|h| h == host))+}++/// A plain explanation of why a program couldn't run over ssh.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SshFailure {+ pub what: String,+ pub fix: String,+}++/// What ssh's own failure messages mean: (text in ssh's output, what happened, what to do).+const SSH_FAILURES: &[(&str, &str, &str)] = &[+ (+ "exec request failed",+ "the computer accepted the login but wouldn't start the program",+ "Check that this computer lets you run programs over ssh and hasn't run out of processes or memory.",+ ),+ ("permission denied", "the login was refused", "Set up an ssh key or agent for this computer; Craft Anything can't type a password."),+ ("host key verification failed", "this computer's identity isn't trusted yet", "Connect once from a terminal and accept its host key."),+ ("could not resolve hostname", "that computer's name wasn't found", "Check the name in Settings → AI and in ~/.ssh/config."),+ ("connection refused", "the computer refused the connection", "Check that its ssh server is running and the port is right."),+ ("timed out", "the computer didn't answer in time", "Check that it's on and reachable from this network."),+ ("no route to host", "the computer can't be reached from this network", "Check that it's on and reachable from this network."),+ ("connection closed", "the connection dropped", "Try again; if it keeps happening, check the computer's ssh server."),+ ("connection reset", "the connection dropped", "Try again; if it keeps happening, check the computer's ssh server."),+ ("broken pipe", "the connection dropped", "Try again; if it keeps happening, check the computer's ssh server."),+];++/// ssh's own exit code for "ssh failed"; any other code is the remote program's.+const SSH_FAILED: i32 = 255;+/// A POSIX shell's exit code for "command not found".+const NOT_FOUND: i32 = 127;++/// Why running `program` on `host` failed, when the failure says. A git server comes first because+/// it fails in many ways.+pub fn diagnose(host: &str, program: &str, git_server: bool, code: Option<i32>, stderr: &str) -> Option<SshFailure> {+ if git_server {+ return Some(SshFailure {+ what: format!("{host} is a git server, not a computer that can run {program}"),+ fix: format!("In Settings → AI, remove the AI that uses {host}, then add one on this computer or on a computer you can log in to."),+ });+ }+ match code {+ Some(NOT_FOUND) => Some(SshFailure {+ what: format!("{program} wasn't found on {host}"),+ fix: format!(+ "Install it there. If it's already installed, ssh sessions may not load your shell's PATH: set the full path in Settings → AI, or add it to the PATH in your shell's startup file on {host}."+ ),+ }),+ Some(SSH_FAILED) => {+ let text = stderr.to_ascii_lowercase();+ let (_, what, fix) = SSH_FAILURES.iter().find(|(needle, _, _)| text.contains(needle))?;+ Some(SshFailure { what: (*what).to_string(), fix: (*fix).to_string() })+ }+ _ => None,+ }+}++/// A command that tests `program` on `host`, without any prompt.+pub fn check_command(host: &str, program: &str) -> String {+ format!("ssh -o BatchMode=yes -T {} -- {} --version", shell_quote(host), shell_quote(program))+}++fn hosts_from_file(path: &Path, base: &Path, depth: u32, parse: fn(&str) -> Vec<String>) -> Vec<String> {if depth > 4 {return Vec::new();}@@ -44,7 +110,7 @@ fn hosts_from_file(path: &Path, base: &Path, depth: u32) -> Vec<String> {Ok(m) if m.len() <= 1024 * 1024 => std::fs::read_to_string(path).unwrap_or_default(),_ => return Vec::new(),};- let mut out = parse_hosts(&text);+ let mut out = parse(&text);for inc in includes(&text) {let p = if inc.starts_with('/') {PathBuf::from(&inc)@@ -60,7 +126,7 @@ fn hosts_from_file(path: &Path, base: &Path, depth: u32) -> Vec<String> {vec![p]};for f in files {- for h in hosts_from_file(&f, base, depth + 1) {+ for h in hosts_from_file(&f, base, depth + 1, parse) {if !out.contains(&h) {out.push(h);}@@ -105,7 +171,24 @@ fn is_git_host(name: &str) -> bool {/// Concrete `Host` names in an ssh config text, without git servers: a host named after one, or/// whose block has a git server's `HostName` or `User git`.pub fn parse_hosts(text: &str) -> Vec<String> {- // One entry per `Host` (or `Match`) line: its names, and whether it points at a git server.+ let blocks = host_blocks(text);+ let git: Vec<&String> = blocks.iter().filter(|b| b.1).flat_map(|b| &b.0).collect();+ let mut out: Vec<String> = Vec::new();+ for name in blocks.iter().filter(|b| !b.1).flat_map(|b| &b.0) {+ if !git.contains(&name) && !out.contains(name) {+ out.push(name.clone());+ }+ }+ out+}++/// The `Host` names in an ssh config text that lead to a git server.+fn git_aliases(text: &str) -> Vec<String> {+ host_blocks(text).into_iter().filter(|b| b.1).flat_map(|b| b.0).collect()+}++/// One entry per `Host` (or `Match`) line: its names, and whether it points at a git server.+fn host_blocks(text: &str) -> Vec<(Vec<String>, bool)> {let mut blocks: Vec<(Vec<String>, bool)> = Vec::new();for line in text.lines() {let l = line.trim();@@ -126,14 +209,7 @@ pub fn parse_hosts(text: &str) -> Vec<String> {*git |= (k.eq_ignore_ascii_case("hostname") && is_git_host(v)) || (k.eq_ignore_ascii_case("user") && v == "git");}}- let git: Vec<&String> = blocks.iter().filter(|b| b.1).flat_map(|b| &b.0).collect();- let mut out: Vec<String> = Vec::new();- for name in blocks.iter().filter(|b| !b.1).flat_map(|b| &b.0) {- if !git.contains(&name) && !out.contains(name) {- out.push(name.clone());- }- }- out+ blocks}/// A local port forwarded to a server on a remote host (`ssh -N -L`), owned and killed on drop.@@ -209,13 +285,38 @@ mod tests {assert_eq!(parse_hosts(cfg), vec!["box", "spaced", "github.community"]);}+ #[test]+ fn an_alias_for_a_git_server_is_known_as_one() {+ let cfg = "Host github.com-work\n HostName github.com\nHost forge\n HostName git.example.org\n User git\nHost gpu\n HostName 10.0.0.2\n";+ assert_eq!(git_aliases(cfg), ["github.com-work", "forge"]);+ }++ #[test]+ fn failures_are_explained_in_plain_words() {+ // Reproduced against GitHub: it logs you in, then refuses to start anything.+ let git = diagnose("github.com-work", "claude", true, Some(255), "exec request failed on channel 0").unwrap();+ assert!(git.what.contains("github.com-work is a git server"), "{}", git.what);+ assert!(git.fix.contains("Settings → AI"));+ // So does its other answer, which exits 1.+ assert!(diagnose("g", "claude", true, Some(1), "Invalid command: claude").is_some());++ let refused = diagnose("gpu", "claude", false, Some(255), "exec request failed on channel 0\n").unwrap();+ assert!(refused.what.contains("wouldn't start the program"));+ assert!(diagnose("gpu", "claude", false, Some(255), "me@gpu: Permission denied (publickey).").unwrap().fix.contains("ssh key"));+ assert!(diagnose("gpu", "claude", false, Some(127), "sh: claude: command not found").unwrap().what.contains("wasn't found on gpu"));+ // The remote program's own failure, or ssh's unknown one, isn't guessed at.+ assert!(diagnose("gpu", "claude", false, Some(1), "Permission denied").is_none());+ assert!(diagnose("gpu", "claude", false, Some(255), "something new").is_none());+ assert_eq!(check_command("gpu", "claude"), "ssh -o BatchMode=yes -T gpu -- claude --version");+ }+#[test]fn includes_are_followed() {let dir = tempfile::tempdir().unwrap();std::fs::create_dir(dir.path().join("config.d")).unwrap();std::fs::write(dir.path().join("config.d").join("work"), "Host work-box\n").unwrap();std::fs::write(dir.path().join("config"), "Include config.d/*\nHost home\n").unwrap();- assert_eq!(hosts_from_file(&dir.path().join("config"), dir.path(), 0), vec!["home", "work-box"]);+ assert_eq!(hosts_from_file(&dir.path().join("config"), dir.path(), 0, parse_hosts), vec!["home", "work-box"]);}#[test]diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex a0a628a6..8576c8e4 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -239,7 +239,7 @@ fn anthropic_refusal_and_http_errors() {assert!(ev.iter().any(|e| matches!(e, AgentEvent::Error { message, .. } if message.contains("declined"))));let ev = run(&mut c, "q2");assert!(- ev.iter().any(|e| matches!(e, AgentEvent::Error { message, remediation: Some(r) } if message.contains("invalid x-api-key") && r.contains("key"))),+ ev.iter().any(|e| matches!(e, AgentEvent::Error { message, remediation: Some(r), .. } if message.contains("invalid x-api-key") && r.contains("key"))),"{ev:?}");}diff --git a/crates/engine/src/feed.rs b/crates/engine/src/feed.rsindex 8304b21a..c7c605a9 100644--- a/crates/engine/src/feed.rs+++ b/crates/engine/src/feed.rs@@ -61,6 +61,9 @@ pub enum FeedItem {Error {message: String,remediation: Option<String>,+ /// A log with everything known about the failure, to open and inspect.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ log: Option<std::path::PathBuf>,},/// The person paused the run (not a failure); a message or Continue carries on.Paused,@@ -116,7 +119,7 @@ pub fn history(ws: &Workspace) -> Vec<FeedItem> {feed.push(FeedItem::Agent { text: m.last_reply.clone(), streaming: false });}if matches!(m.status, Status::NeedsYou) && !m.note.is_empty() {- feed.push(FeedItem::Error { message: m.note.clone(), remediation: None });+ feed.push(FeedItem::Error { message: m.note.clone(), remediation: None, log: None });}feed.extend(Inbox::new(ws.inbox_dir()).pending().into_iter().map(|request| FeedItem::Ask { request, answer: None }));feeddiff --git a/crates/engine/src/tools/adb_tools.rs b/crates/engine/src/tools/adb_tools.rsindex 1e4dc165..e25614d2 100644--- a/crates/engine/src/tools/adb_tools.rs+++ b/crates/engine/src/tools/adb_tools.rs@@ -590,7 +590,7 @@ fn exec_error(what: &str, out: &Output) -> ToolError {let tail = tail_text(&out.stderr_text());let msg = tail.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output").trim().to_string();ToolError::new(ErrorCode::ProgramFailed, format!("{what} failed: {msg}"))- .with_remediation("Run the adb command by hand to see the full message.")+ .with_remediation(format!("What adb printed last:\n{}", craft_anything_platform::process::output_excerpt(&tail))).with_details(json!({"exit_code": out.code, "stderr_tail": tail}))}@@ -990,8 +990,10 @@ fn adb_app_download(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, Tool}pub(crate) fn pull_error(path: &str, out: &Output) -> ToolError {- ToolError::new(ErrorCode::ProgramFailed, format!("adb pull of {path} failed: {}", tail_text(&out.stderr_text()).trim()))- .with_remediation("Check the device path exists and is readable; run adb pull by hand to see the full message.")+ ToolError::new(ErrorCode::ProgramFailed, format!("adb pull of {path} failed: {}", tail_text(&out.stderr_text()).trim())).with_remediation(format!(+ "Check the device path exists and is readable. To try it yourself, run:\nadb pull {}",+ craft_anything_platform::process::printable_command(std::ffi::OsStr::new(path), &[] as &[&str])+ ))}fn adb_file_download(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {diff --git a/crates/engines/src/adb.rs b/crates/engines/src/adb.rsindex 52a8268e..783efc1f 100644--- a/crates/engines/src/adb.rs+++ b/crates/engines/src/adb.rs@@ -158,7 +158,10 @@ fn adb_failed(what: &str, out: &Output) -> ToolError {};let msg = tail.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output").trim().to_string();ToolError::new(ErrorCode::ProgramFailed, format!("{what} failed: {msg}"))- .with_remediation("Run the adb command by hand to see the full message; check the device is connected and authorised.")+ .with_remediation(format!(+ "Check the device is connected and authorised (`adb devices`). What adb printed last:\n{}",+ craft_anything_platform::process::output_excerpt(&tail)+ )).with_details(serde_json::json!({"exit_code": out.code, "stderr_tail": tail}))}diff --git a/crates/engines/src/frida.rs b/crates/engines/src/frida.rsindex ee8a9a93..880292d0 100644--- a/crates/engines/src/frida.rs+++ b/crates/engines/src/frida.rs@@ -247,7 +247,10 @@ fn cli_failed(what: &str, out: &Output) -> ToolError {};let msg = tail.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output").trim().to_string();ToolError::new(ErrorCode::ProgramFailed, format!("{what} failed: {msg}"))- .with_remediation("Check the device is reachable and frida-server is running on it; run the command by hand to see the full message.")+ .with_remediation(format!(+ "Check the device is reachable and frida-server is running on it. What Frida printed last:\n{}",+ craft_anything_platform::process::output_excerpt(&tail)+ )).with_details(serde_json::json!({"exit_code": out.code, "stderr_tail": tail}))}diff --git a/crates/platform/src/process.rs b/crates/platform/src/process.rsindex e099ea93..2e03c1f7 100644--- a/crates/platform/src/process.rs+++ b/crates/platform/src/process.rs@@ -261,8 +261,9 @@ impl Process {/// Run to completion; a non-zero exit becomes an `program_failed` error with the stderr tail.pub fn run_checked(self) -> Result<Output, ToolError> {let name = self.display();+ let command = printable_command(&self.program, &self.args);let out = self.run()?;- if out.success { Ok(out) } else { Err(nonzero_error(&name, &out)) }+ if out.success { Ok(out) } else { Err(nonzero_error_with(&name, &out, Some(&command))) }}/// Start the child and supervise it on a background thread.@@ -380,17 +381,87 @@ fn tail(bytes: &[u8], n: usize) -> String {String::from_utf8_lossy(bytes.get(start..).unwrap_or_default()).into_owned()}+/// Longest argument shown whole in [`printable_command`]; longer ones are usually prompts or+/// generated data.+const MAX_SHOWN_ARG: usize = 200;+/// Lines of a failed program's output shown in its error.+const SHOWN_OUTPUT_LINES: usize = 15;+const SHOWN_OUTPUT_LINE_CHARS: usize = 300;++/// A command as a person could type it, for errors and logs. Values of secret-looking flags are+/// masked and very long arguments left out (each says what it replaced), so it's safe to show.+pub fn printable_command<S: AsRef<OsStr>>(program: &OsStr, args: &[S]) -> String {+ let mut words = vec![shell_word(&program.to_string_lossy())];+ let mut mask_next = false;+ for arg in args {+ let arg = arg.as_ref().to_string_lossy();+ let secret_flag = arg.starts_with('-') && is_secret_name(arg.split('=').next().unwrap_or_default());+ words.push(if mask_next {+ "<hidden>".to_string()+ } else if let (true, Some((flag, _))) = (secret_flag, arg.split_once('=')) {+ format!("{}=<hidden>", shell_word(flag))+ } else if arg.chars().count() > MAX_SHOWN_ARG {+ format!("<{} characters left out>", arg.chars().count())+ } else {+ shell_word(&arg)+ });+ mask_next = secret_flag && !arg.contains('=');+ }+ words.join(" ")+}++fn is_secret_name(flag: &str) -> bool {+ let flag = flag.to_ascii_lowercase();+ ["token", "secret", "password", "passwd", "api-key", "api_key", "apikey", "credential"].iter().any(|s| flag.contains(s))+}++fn shell_word(s: &str) -> String {+ if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:@%+,\\".contains(c)) {+ return s.to_string();+ }+ format!("'{}'", s.replace('\'', "'\\''"))+}++/// The last lines of what a program printed, each cut to a readable length.+pub fn output_excerpt(text: &str) -> String {+ let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();+ let from = lines.len().saturating_sub(SHOWN_OUTPUT_LINES);+ lines+ .get(from..)+ .unwrap_or_default()+ .iter()+ .map(|l| {+ if l.chars().count() > SHOWN_OUTPUT_LINE_CHARS {+ format!("{}…", l.chars().take(SHOWN_OUTPUT_LINE_CHARS).collect::<String>())+ } else {+ l.to_string()+ }+ })+ .collect::<Vec<_>>()+ .join("\n")+}+/// The error for a non-zero exit, with the last part of stderr (or stdout) for context.pub fn nonzero_error(name: &str, out: &Output) -> ToolError {+ nonzero_error_with(name, out, None)+}++/// [`nonzero_error`], also saying what was run so the person can run it themselves.+pub fn nonzero_error_with(name: &str, out: &Output, command: Option<&str>) -> ToolError {let code = out.code.map(|c| c.to_string()).unwrap_or_else(|| "a signal".into());let stderr_tail = tail(&out.stderr, 2000);let context = if stderr_tail.trim().is_empty() { tail(&out.stdout, 2000) } else { stderr_tail };let first_line = context.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or_default().trim().to_string();let msg =if first_line.is_empty() { format!("{name} stopped with exit code {code}.") } else { format!("{name} stopped with exit code {code}: {first_line}") };+ let excerpt = output_excerpt(&context);+ let mut said = if excerpt.is_empty() { format!("{name} printed nothing.") } else { format!("What {name} printed last:\n{excerpt}") };+ if let Some(command) = command {+ said.push_str(&format!("\n\nTo try it yourself, run:\n{command}"));+ }ToolError::new(ErrorCode::ProgramFailed, msg)- .with_remediation(format!("Check the output below; run {name} by hand to see the full message."))- .with_details(serde_json::json!({"exit_code": out.code, "output_tail": context}))+ .with_remediation(said)+ .with_details(serde_json::json!({"exit_code": out.code, "output_tail": context, "command": command}))}/// A child being supervised on a background thread. Dropping it kills the child.@@ -1055,6 +1126,9 @@ mod tests {assert_eq!(out.stdout_text(), "hello\n");assert_eq!(out.stderr_text(), "oops\n");let err = Process::new("sh").args(["-c", "echo bad thing >&2; exit 1"]).run_checked().unwrap_err();+ let help = err.remediation.clone().unwrap();+ assert!(help.contains("bad thing") && help.contains("sh -c 'echo bad thing >&2; exit 1'"), "says what it printed and what ran: {help}");+ assert!(!help.contains("by hand"), "{help}");assert_eq!(err.code, ErrorCode::ProgramFailed);assert!(err.message.contains("bad thing"), "{}", err.message);}diff --git a/crates/setup/src/doctor.rs b/crates/setup/src/doctor.rsindex 4e8831ac..8f348624 100644--- a/crates/setup/src/doctor.rs+++ b/crates/setup/src/doctor.rs@@ -202,7 +202,7 @@ pub fn mcp_self_test(program: &str, args: &[String], timeout: Duration) -> CheckOk(o) => o,Err(e) => {return Check::new(name, CheckStatus::Fail, format!("The MCP server didn't answer: {}", e.message))- .fix(e.remediation.unwrap_or_else(|| "Run `craft-anything-cli mcp` by hand to see the error.".into()));+ .fix(e.remediation.unwrap_or_else(|| "Run this in a terminal to see the error: craft-anything-cli mcp".into()));}};let mut init = None;@@ -217,7 +217,7 @@ pub fn mcp_self_test(program: &str, args: &[String], timeout: Duration) -> Check}let Some(init) = init else {return Check::new(name, CheckStatus::Fail, "The MCP server sent no reply to initialize.")- .fix("Run `craft-anything-cli mcp` by hand to see the error.");+ .fix("Run this in a terminal to see the error: craft-anything-cli mcp");};let server = init["result"]["serverInfo"]["name"].as_str().unwrap_or_default();let protocol = init["result"]["protocolVersion"].as_str().unwrap_or_default();diff --git a/crates/ui-egui/src/chat.rs b/crates/ui-egui/src/chat.rsindex 25af5e3f..14b75b23 100644--- a/crates/ui-egui/src/chat.rs+++ b/crates/ui-egui/src/chat.rs@@ -70,12 +70,12 @@ pub fn apply_event(chat: &mut Vec<ChatItem>, e: AgentEvent) {}}}- AgentEvent::Error { message, remediation } => {+ AgentEvent::Error { message, remediation, log } => {end_streaming(chat);if matches!(chat.last(), Some(ChatItem::Status(_))) {chat.pop();}- chat.push(ChatItem::Error { message, remediation });+ chat.push(ChatItem::Error { message, remediation, log });}}}@@ -274,6 +274,7 @@ fn history(app: &mut CraftApp, ui: &mut Ui, dense: bool, pad: f32, max_w: f32) {for a in actions {match a {ChatAction::Consent(id, ans) => app.answer_consent(&id, ans),+ ChatAction::OpenLog(path) => app.open_log(&path),ChatAction::AddBrain => {app.state.settings_open = true;app.state.settings_tab = crate::state::SettingsTab::Ai;@@ -344,6 +345,7 @@ fn composer(app: &mut CraftApp, ui: &mut Ui, width: f32, dense: bool) {enum ChatAction {Consent(String, ConsentAnswer),AddBrain,+ OpenLog(std::path::PathBuf),}pub(crate) fn bubble(t: &Tokens, user: bool, dense: bool) -> egui::Frame {@@ -465,7 +467,7 @@ fn item_ui(ui: &mut Ui, item: &ChatItem, beginner: bool, dense: bool, open: bool}});}- ChatItem::Error { message, remediation } => {+ ChatItem::Error { message, remediation, log } => {egui::Frame::new().fill(t.card).stroke(egui::Stroke::new(1.0, t.danger.gamma_multiply(0.6)))@@ -480,6 +482,11 @@ fn item_ui(ui: &mut Ui, item: &ChatItem, beginner: bool, dense: bool, open: boolif let Some(r) = remediation {ui.add(egui::Label::new(RichText::new(r).color(t.text_dim)).wrap());}+ if let Some(l) = log+ && widgets::open_log_button(ui, l)+ {+ actions.push(ChatAction::OpenLog(l.clone()));+ }});}ChatItem::AddBrain => {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex a42426e7..7d2a6bed 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -836,6 +836,13 @@ impl CraftApp {}}+ /// Show a failure log in the system's viewer for text files.+ pub(crate) fn open_log(&mut self, path: &std::path::Path) {+ if let Err(e) = craft_anything_platform::open_path(path) {+ self.toast(format!("{}: {}", e.message, path.display()), true);+ }+ }+/// Open a file or folder as the active target.pub fn open_path(&mut self, path: PathBuf) {let path = if path.is_absolute() { path } else { std::env::current_dir().map(|d| d.join(&path)).unwrap_or(path) };@@ -1004,7 +1011,7 @@ impl CraftApp {if self.state.backend.is_some() && self.conversation.is_none() {match self.hub.start(self.state.backend.as_deref(), self.beginner()) {Ok(c) => self.conversation = Some(c),- Err(e) => self.state.chat.push(ChatItem::Error { message: e.message, remediation: e.remediation }),+ Err(e) => self.state.chat.push(ChatItem::Error { message: e.message, remediation: e.remediation, log: None }),}}if let Some(c) = self.conversation.as_mut() {@@ -1328,7 +1335,7 @@ impl CraftApp {self.state.modal = Some(state::Modal::DeepMode);return;}- Err(e) => self.state.chat.push(ChatItem::Error { message: e.message, remediation: e.remediation }),+ Err(e) => self.state.chat.push(ChatItem::Error { message: e.message, remediation: e.remediation, log: None }),}if cta {self.state.chat.push(ChatItem::AddBrain);diff --git a/crates/ui-egui/src/project.rs b/crates/ui-egui/src/project.rsindex 0187264b..4ed6d8b5 100644--- a/crates/ui-egui/src/project.rs+++ b/crates/ui-egui/src/project.rs@@ -150,7 +150,7 @@ impl CraftApp {match self.launch(ws.clone(), opts) {Ok(Started::Running) => {}Ok(Started::Queued { .. }) => self.toast(tr("Another build is working, so this one waits its turn."), false),- Err(e) => self.state.feed.push(FeedItem::Error { message: e.message, remediation: e.remediation }),+ Err(e) => self.state.feed.push(FeedItem::Error { message: e.message, remediation: e.remediation, log: None }),}self.workspace = Some(ws);self.refresh_projects();@@ -1019,7 +1019,7 @@ fn draw_items(}}FeedItem::Check(c) => check_card(app, ui, ctx, ws, c),- FeedItem::Error { message, remediation } => {+ FeedItem::Error { message, remediation, log } => {egui::Frame::new().fill(t.card).stroke(egui::Stroke::new(1.0, t.danger.gamma_multiply(0.6)))@@ -1034,6 +1034,11 @@ fn draw_items(if let Some(r) = remediation {ui.add(egui::Label::new(RichText::new(r).color(t.text_dim)).wrap());}+ if let Some(l) = log+ && widgets::open_log_button(ui, l)+ {+ app.open_log(l);+ }let last = i + 1 == items.len();// A pause or a stop part-way gets the Continue card below instead.if last && !app.running() && !can_continue(app, ws) {@@ -1622,7 +1627,7 @@ mod tests {assert!(matches!(&feed[3], FeedItem::Agent { text, .. } if text == "Done."));assert!(matches!(&feed[4], FeedItem::Check(_)));assert_eq!(feed.len(), 5, "a successful finish adds nothing");- apply(&mut feed, &ev(AgentEvent::Error { message: "x".into(), remediation: None }));+ apply(&mut feed, &ev(AgentEvent::Error { message: "x".into(), remediation: None, log: None }));apply(&mut feed, &RunEvent::Finished { ok: false, message: "x".into(), paused: false });assert_eq!(feed.iter().filter(|f| matches!(f, FeedItem::Error { .. })).count(), 1, "an explained failure isn't repeated");// A pause isn't a failure: a calm line, not an error card.diff --git a/crates/ui-egui/src/report.rs b/crates/ui-egui/src/report.rsindex 3b39eb72..ca4e1f66 100644--- a/crates/ui-egui/src/report.rs+++ b/crates/ui-egui/src/report.rs@@ -75,7 +75,7 @@ pub fn markdown(chat: &[ChatItem], target: Option<&TargetInfo>, clean_room: bool};let _ = writeln!(out, "- Permission to run *{title}*: {a}\n");}- ChatItem::Error { message, remediation } => {+ ChatItem::Error { message, remediation, .. } => {let _ = writeln!(out, "> ⚠ {message}{}\n", remediation.as_ref().map(|r| format!(" {r}")).unwrap_or_default());}ChatItem::Status(_) | ChatItem::AddBrain => {}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 74ddf42e..b555ee00 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -162,6 +162,9 @@ pub enum ChatItem {Error {message: String,remediation: Option<String>,+ /// A log with everything known about the failure, to open and inspect.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ log: Option<std::path::PathBuf>,},/// "Add a brain" and similar calls to action.AddBrain,diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex e232a5e4..31d497fd 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -454,3 +454,9 @@ pub fn working_since(ui: &mut Ui, title: &str, detail: Option<&str>, began: Opti});animate(ui, FRAME);}++/// The button that opens a failure's log; hovering shows where the log is. True when clicked.+pub fn open_log_button(ui: &mut Ui, path: &std::path::Path) -> bool {+ ui.add_space(6.0);+ secondary(ui, None, "Open log").on_hover_text(path.display().to_string()).clicked()+}diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rsindex 11ef6688..f91ce27c 100644--- a/crates/ui-egui/tests/smoke.rs+++ b/crates/ui-egui/tests/smoke.rs@@ -705,6 +705,22 @@ fn mode_switch_and_deep_toggle() {assert_eq!(h.state().settings.mode, Mode::Beginner);}+#[test]+fn a_failure_with_a_log_offers_to_open_it_and_one_without_does_not() {+ let mut h = harness(|| {+ let mut a = demo::app(demo::engine(Mode::Beginner, true));+ demo::fill_ask(&mut a);+ a.state.chat = vec![ChatItem::Error { message: "It failed.".into(), remediation: Some("ssh printed: no".into()), log: None }];+ a+ });+ h.run_steps(4);+ h.get_by_label_contains("ssh printed: no");+ assert!(h.query_by_label("Open log").is_none());+ h.state_mut().state.chat = vec![ChatItem::Error { message: "It failed.".into(), remediation: None, log: Some("/tmp/agent.log".into()) }];+ h.run_steps(4);+ h.get_by_label("Open log");+}+#[test]fn ask_screen_renders_every_chat_item_and_consent_answers() {let mut h = harness(|| {diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex fbeeb336..4dbc7b0e 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -656,6 +656,11 @@ Deep mode is its own switch, not tied to Ghidra.- [ ] A live Clean room build of a website and of an app, checked end to end- [ ] A remote (SSH) builder needs a craft-anything-cli that knows `--deep` and `--clean-room`:check its version first and say so when it's older+- [ ] A remote (SSH) builder doesn't get the time limits or effort set through `Process::env`+ (`MCP_TOOL_TIMEOUT`, `CLAUDE_CODE_EFFORT_LEVEL`…): they're set on the local `ssh`, which doesn't+ pass them on. Set them in the remote command+- [ ] Failure logs for the other ways an AI stops (API backends, MCP server start-up), like the+ ones agent CLIs write to `logs/` in the config folder### R2.9 Everyday use: typing, projects, settingsOwner: maintainers · Status: in progressdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 3876b57d..769d6442 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -43,6 +43,10 @@ against a stand-in server, not yet a real Cutter). Every tool is listed in `docs## Known limits+- A failed agent CLI run says what ran and what it printed, and writes a private log to `logs/` in the+ config folder (the newest 50 are kept; the person's message is left out; **Open log** in the app, `log:`+ in the CLI). Checked live against a GitHub ssh alias from the CLI; the button by a UI test, not by+ clicking it in the desktop app. API backends and MCP start-up don't write these logs yet.- Live end-to-end runs (2026-10-18, Windows 10, headless CLI): a website clone reached Readyat 96% likeness in 1.5 min; a small desktop app rebuilt in Rust + egui reached Ready in 9 min (checkedonly by building); a game rebuild in Rust reached Build and was stopped before Check. Thediff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 9a1b2b0a..789582b0 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -296,6 +296,13 @@ and run `cargo xtask secrets` before every commit (the `.githooks/pre-commit` hoUpdate STATUS, the roadmap and generated docs (`cargo xtask tools`, `cargo xtask schemas`) in thesame PR as the change.+**An error that points at nothing.** "Check the output below; run Claude Code by hand" came with no+output below (the event carried only message and remediation) and no command, and the program+that failed was really ssh, talking to a git alias from `~/.ssh/config` that had been offered as a+computer. Say what ran and what it printed, write the rest to a log the person can open (a failed+agent run does: `crate::failure_log`), and never name a next step you don't spell out. Exit 255+from ssh is ssh's own failure: don't blame the remote program. Test a message by causing the failure.+**A filter written for one kind of text, run on another.** The stand-in's secret scan was written forAPI answers, then also ran on recorded scripts: `this.token=t` became `[dropped]` and the scriptsbroke, and "Basic Membership" lost a word. It also tested whole tokens, so a secret inside a URL or