1use std::io::Read;
2use std::path::Path;
3use std::process::{Command as ShellCommand, Stdio};
4use std::time::{Duration, Instant};
5
6use anyhow::{anyhow, Context, Result};
7
8use serde::{Deserialize, Serialize};
9
10use crate::config::Config;
11use crate::resolve::resolve_unit;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct VerifyResult {
16 pub passed: bool,
18 pub exit_code: Option<i32>,
20 pub stdout: String,
22 pub stderr: String,
24 pub timed_out: bool,
26 pub command: String,
28 pub timeout_secs: Option<u64>,
30}
31
32pub fn run_verify(mana_dir: &Path, id: &str) -> Result<Option<VerifyResult>> {
39 let unit = resolve_unit(mana_dir, id)?.unit;
40
41 let verify_cmd = match &unit.verify {
42 Some(cmd) if !cmd.trim().is_empty() => cmd.clone(),
43 _ => return Ok(None),
44 };
45
46 let config = Config::load_with_extends(mana_dir).ok();
47 let timeout_secs =
48 unit.effective_verify_timeout(config.as_ref().and_then(|c| c.verify_timeout));
49
50 let project_root = mana_dir
51 .parent()
52 .ok_or_else(|| anyhow!("Cannot determine project root from units dir"))?;
53
54 run_verify_command(&verify_cmd, project_root, timeout_secs).map(Some)
55}
56
57pub fn run_verify_command(
62 verify_cmd: &str,
63 working_dir: &Path,
64 timeout_secs: Option<u64>,
65) -> Result<VerifyResult> {
66 let mut child = ShellCommand::new("sh")
67 .args(["-c", verify_cmd])
68 .current_dir(working_dir)
69 .stdout(Stdio::piped())
70 .stderr(Stdio::piped())
71 .spawn()
72 .with_context(|| format!("Failed to spawn verify command: {}", verify_cmd))?;
73
74 let stdout_thread = {
76 let stdout = child.stdout.take().expect("stdout is piped");
77 std::thread::spawn(move || {
78 let mut buf = Vec::new();
79 let mut reader = std::io::BufReader::new(stdout);
80 let _ = reader.read_to_end(&mut buf);
81 String::from_utf8_lossy(&buf).to_string()
82 })
83 };
84 let stderr_thread = {
85 let stderr = child.stderr.take().expect("stderr is piped");
86 std::thread::spawn(move || {
87 let mut buf = Vec::new();
88 let mut reader = std::io::BufReader::new(stderr);
89 let _ = reader.read_to_end(&mut buf);
90 String::from_utf8_lossy(&buf).to_string()
91 })
92 };
93
94 let timeout = timeout_secs.map(Duration::from_secs);
95 let start = Instant::now();
96
97 let (timed_out, exit_status) = loop {
98 match child
99 .try_wait()
100 .with_context(|| "Failed to poll verify process")?
101 {
102 Some(status) => break (false, Some(status)),
103 None => {
104 if let Some(limit) = timeout {
105 if start.elapsed() >= limit {
106 let _ = child.kill();
107 let _ = child.wait();
108 break (true, None);
109 }
110 }
111 std::thread::sleep(Duration::from_millis(50));
112 }
113 }
114 };
115
116 let stdout = stdout_thread.join().unwrap_or_default();
117 let stderr = stderr_thread.join().unwrap_or_default();
118
119 let exit_code = exit_status.and_then(|s| s.code());
120 let passed = !timed_out && exit_status.map(|s| s.success()).unwrap_or(false);
121
122 Ok(VerifyResult {
123 passed,
124 exit_code,
125 stdout,
126 stderr,
127 timed_out,
128 command: verify_cmd.to_string(),
129 timeout_secs,
130 })
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use crate::config::Config;
137 use crate::ops::create::{self, tests::minimal_params};
138 use std::fs;
139 use std::path::PathBuf;
140 use tempfile::TempDir;
141
142 fn setup() -> (TempDir, PathBuf) {
143 let dir = TempDir::new().unwrap();
144 let bd = dir.path().join(".mana");
145 fs::create_dir(&bd).unwrap();
146 Config {
147 project: "test".to_string(),
148 next_id: 1,
149 auto_close_parent: true,
150 run: None,
151 plan: None,
152 max_loops: 10,
153 max_concurrent: 4,
154 poll_interval: 30,
155 extends: vec![],
156 rules_file: None,
157 file_locking: false,
158 worktree: false,
159 on_close: None,
160 on_fail: None,
161 verify_timeout: None,
162 review: None,
163 user: None,
164 user_email: None,
165 auto_commit: false,
166 commit_template: None,
167 research: None,
168 run_model: None,
169 plan_model: None,
170 review_model: None,
171 research_model: None,
172 batch_verify: false,
173 memory_reserve_mb: 0,
174 notify: None,
175 }
176 .save(&bd)
177 .unwrap();
178 (dir, bd)
179 }
180
181 #[test]
182 fn verify_passing_command() {
183 let (_dir, bd) = setup();
184 let mut params = minimal_params("Task");
185 params.verify =
186 Some("grep -q 'project: test' .mana/config.yaml && printf hello".to_string());
187 create::create(&bd, params).unwrap();
188
189 let result = run_verify(&bd, "1").unwrap().unwrap();
190 assert!(result.passed);
191 assert_eq!(result.exit_code, Some(0));
192 assert!(result.stdout.contains("hello"));
193 assert!(!result.timed_out);
194 }
195
196 #[test]
197 fn verify_failing_command() {
198 let (_dir, bd) = setup();
199 let mut params = minimal_params("Task");
200 params.verify = Some("exit 1".to_string());
201 create::create(&bd, params).unwrap();
202
203 let result = run_verify(&bd, "1").unwrap().unwrap();
204 assert!(!result.passed);
205 assert_eq!(result.exit_code, Some(1));
206 assert!(!result.timed_out);
207 }
208
209 #[test]
210 fn verify_no_command_returns_none() {
211 let (_dir, bd) = setup();
212 create::create(&bd, minimal_params("Task")).unwrap();
213
214 let result = run_verify(&bd, "1").unwrap();
215 assert!(result.is_none());
216 }
217
218 #[test]
219 fn verify_nonexistent_unit() {
220 let (_dir, bd) = setup();
221 assert!(run_verify(&bd, "99").is_err());
222 }
223
224 #[test]
225 fn verify_captures_stderr() {
226 let (_dir, bd) = setup();
227 let mut params = minimal_params("Task");
228 params.verify =
229 Some("grep -q 'project: test' .mana/config.yaml && printf err >&2".to_string());
230 create::create(&bd, params).unwrap();
231
232 let result = run_verify(&bd, "1").unwrap().unwrap();
233 assert!(result.passed);
234 assert!(result.stderr.contains("err"));
235 }
236
237 #[test]
238 fn run_verify_command_directly() {
239 let dir = TempDir::new().unwrap();
240 let result = run_verify_command("echo direct", dir.path(), None).unwrap();
241 assert!(result.passed);
242 assert!(result.stdout.contains("direct"));
243 }
244
245 #[test]
246 fn run_verify_command_timeout() {
247 let dir = TempDir::new().unwrap();
248 let result = run_verify_command("sleep 10", dir.path(), Some(1)).unwrap();
249 assert!(!result.passed);
250 assert!(result.timed_out);
251 }
252}