返回 CodeWhale
test_runner.rs
根目录 / crates / engine / src / tools / test_runner.rs
1 //! Cargo test runner tool: `run_tests`.
2 //!
3 //! `cargo test` runs workspace code, so this tool follows the same explicit
4 //! approval policy as the other code-executing tools.
5
6 use std::collections::HashMap;
7 use std::path::Path;
8 use std::time::{Duration, Instant};
9
10 use async_trait::async_trait;
11 use serde::{Deserialize, Serialize};
12 use serde_json::{Value, json};
13
14 use super::cargo_failure_summary::summarize_cargo_failure;
15 use super::shell::{
16 SharedShellManager, ShellLaunchNotStarted, ShellManager, ShellResult, ShellStatus,
17 };
18 use super::spec::{
19 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
20 optional_bool, optional_str,
21 };
22
23 use codewhale_dependencies::ExternalTool;
24
25 pub(super) const DEFAULT_AUTO_BACKGROUND_TIMEOUT_MS: u64 = 30_000;
26 const MAX_RUN_TESTS_TIMEOUT_MS: u64 = 30 * 60 * 1_000;
27 const BACKGROUND_JOB_TIMEOUT_MS: u64 = 600_000;
28 const FOREGROUND_POLL_INITIAL_MS: u64 = 5;
29 const FOREGROUND_POLL_MAX_MS: u64 = 100;
30
31 /// Tool for running `cargo test` in the workspace root.
32 pub struct RunTestsTool;
33
34 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
35 struct RunTestsOutput {
36 success: bool,
37 #[serde(flatten)]
38 capture: Option<TestCapture>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 exit_code: Option<i32>,
41 stdout: String,
42 stderr: String,
43 command: String,
44 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
45 timed_out: bool,
46 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
47 backgrounded: bool,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 status: Option<String>,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
51 task_id: Option<String>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 last_output_age_ms: Option<u64>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 progress: Option<String>,
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57 zero_tests_matched: bool,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 tests_executed: Option<usize>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 tests_filtered_out: Option<usize>,
62 #[serde(default, skip_serializing_if = "Option::is_none")]
63 warning: Option<String>,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
65 summary: Option<String>,
66 }
67
68 #[derive(Debug, Clone, Serialize, Deserialize)]
69 struct TestCapture {
70 output_complete: bool,
71 stdout_total_len: usize,
72 stderr_total_len: usize,
73 stdout_omitted: usize,
74 stderr_omitted: usize,
75 }
76
77 impl From<&ShellResult> for TestCapture {
78 fn from(snapshot: &ShellResult) -> Self {
79 Self {
80 output_complete: !snapshot.stdout_truncated
81 && !snapshot.stderr_truncated
82 && snapshot.stdout_omitted == 0
83 && snapshot.stderr_omitted == 0,
84 stdout_total_len: snapshot.stdout_len,
85 stderr_total_len: snapshot.stderr_len,
86 stdout_omitted: snapshot.stdout_omitted,
87 stderr_omitted: snapshot.stderr_omitted,
88 }
89 }
90 }
91
92 #[derive(Debug, Clone, Default, PartialEq, Eq)]
93 pub(crate) struct ZeroTestDetection {
94 pub zero_tests_matched: bool,
95 pub tests_executed: Option<usize>,
96 pub tests_filtered_out: Option<usize>,
97 pub runner: Option<&'static str>,
98 pub reason: Option<String>,
99 }
100
101 #[async_trait]
102 impl ToolSpec for RunTestsTool {
103 fn name(&self) -> &'static str {
104 "run_tests"
105 }
106
107 fn model_visible(&self) -> bool {
108 false
109 }
110
111 fn description(&self) -> &'static str {
112 "Run `cargo test` in the workspace root with optional extra arguments. Auto-backgrounds after 30s by default unless background=false; set background=true to detach immediately."
113 }
114
115 fn input_schema(&self) -> Value {
116 json!({
117 "type": "object",
118 "properties": {
119 "args": {
120 "type": "string",
121 "description": "Optional extra arguments to pass to `cargo test` (shell-style)."
122 },
123 "all_features": {
124 "type": "boolean",
125 "description": "When true, include `--all-features`."
126 },
127 "cwd": {
128 "type": "string",
129 "description": "Optional working directory, relative to the workspace, to run `cargo test` in. Must exist inside the workspace."
130 },
131 "background": {
132 "type": "boolean",
133 "description": "When true, start immediately as a background job and return task_id. When omitted, wait up to timeout_ms (default 30000ms) and auto-background if still running. When false, block until completion or timeout_ms."
134 },
135 "timeout_ms": {
136 "type": "integer",
137 "minimum": 1,
138 "maximum": MAX_RUN_TESTS_TIMEOUT_MS,
139 "description": "Foreground wait budget in milliseconds before auto-backgrounding (default 30000), or maximum blocking timeout when background=false."
140 }
141 },
142 "additionalProperties": false
143 })
144 }
145
146 fn capabilities(&self) -> Vec<ToolCapability> {
147 vec![ToolCapability::ExecutesCode, ToolCapability::Sandboxable]
148 }
149
150 fn approval_requirement(&self) -> ApprovalRequirement {
151 // `run_tests` declares `ToolCapability::ExecutesCode` — match the
152 // default approval policy for code-executing tools.
153 ApprovalRequirement::Required
154 }
155
156 fn starts_detached_for(&self, input: &Value) -> bool {
157 input.get("background").and_then(Value::as_bool) == Some(true)
158 }
159
160 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
161 crate::tools::execution_envelope::enforce_tool_denial(context, self.name(), &input)?;
162 let all_features = optional_bool(&input, "all_features", false)?;
163 let extra_args = optional_str(&input, "args")?
164 .map(str::trim)
165 .filter(|s| !s.is_empty());
166 let explicit_background = match input.get("background") {
167 None | Some(Value::Null) => None,
168 Some(Value::Bool(flag)) => Some(*flag),
169 Some(_) => {
170 return Err(ToolError::invalid_input(
171 "Field 'background' must be a boolean",
172 ));
173 }
174 };
175 let explicit_background = if context
176 .child_host
177 .as_ref()
178 .is_some_and(|child| !child.can_collect_background_tests())
179 {
180 if explicit_background == Some(true) {
181 return Err(ToolError::invalid_input(
182 "This child cannot collect a background test job; run in the foreground",
183 ));
184 }
185 Some(false)
186 } else {
187 explicit_background
188 };
189 let timeout_ms = match input.get("timeout_ms") {
190 None | Some(Value::Null) => None,
191 Some(value) => {
192 let ms = value.as_u64().ok_or_else(|| {
193 ToolError::invalid_input("Field 'timeout_ms' must be a positive integer")
194 })?;
195 if !(1..=MAX_RUN_TESTS_TIMEOUT_MS).contains(&ms) {
196 return Err(ToolError::invalid_input(format!(
197 "timeout_ms must be between 1 and {MAX_RUN_TESTS_TIMEOUT_MS}"
198 )));
199 }
200 Some(ms)
201 }
202 };
203 let workdir = match optional_str(&input, "cwd")?
204 .map(str::trim)
205 .filter(|s| !s.is_empty())
206 {
207 None => context.workspace.clone(),
208 Some(raw) => context.resolve_existing_dir(raw, "cwd")?,
209 };
210
211 let mut args = vec!["test".to_string()];
212 if all_features {
213 args.push("--all-features".to_string());
214 }
215 let mut extra_tokens = Vec::new();
216 if let Some(extra) = extra_args {
217 let split = shlex::split(extra).ok_or_else(|| {
218 ToolError::invalid_input("Failed to parse 'args' as shell-style tokens")
219 })?;
220 extra_tokens = split.clone();
221 args.extend(split);
222 }
223 let filtered = has_test_filter_args(&extra_tokens);
224
225 if context
226 .cancel_token
227 .as_ref()
228 .is_some_and(|token| token.is_cancelled())
229 {
230 return Err(ToolError::cancelled("cargo test cancelled"));
231 }
232
233 let command_str = format_command(&workdir, &args);
234 match explicit_background {
235 Some(true) => start_background_cargo(&workdir, &args, &command_str, context),
236 None => {
237 let wait =
238 Duration::from_millis(timeout_ms.unwrap_or(DEFAULT_AUTO_BACKGROUND_TIMEOUT_MS));
239 run_cargo_with_auto_background(
240 &workdir,
241 &args,
242 &command_str,
243 context,
244 wait,
245 filtered,
246 )
247 .await
248 }
249 Some(false) => {
250 let timeout = timeout_ms
251 .map(Duration::from_millis)
252 .unwrap_or(RUN_TESTS_TIMEOUT);
253 let run = run_cargo(&workdir, &args, context, timeout).await?;
254 let output = run.output;
255 let mut stderr = String::from_utf8_lossy(&output.stderr).into_owned();
256 if run.stopped {
257 stderr.push_str(&format!(
258 "\n[run_tests: stopped after {} s; the output above is everything cargo wrote before it was killed]",
259 timeout.as_secs()
260 ));
261 }
262 let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
263 let exit_code = output.status.code().unwrap_or(-1);
264 finish_completed_tests(
265 RunTestsOutput {
266 success: !run.stopped && output.status.success(),
267 exit_code: Some(exit_code),
268 stdout,
269 stderr,
270 command: command_str,
271 timed_out: run.stopped,
272 ..Default::default()
273 },
274 filtered,
275 )
276 }
277 }
278 }
279 }
280
281 fn finish_completed_tests(
282 mut output: RunTestsOutput,
283 filtered: bool,
284 ) -> Result<ToolResult, ToolError> {
285 let output_complete = output
286 .capture
287 .as_ref()
288 .is_none_or(|capture| capture.output_complete);
289 let detection = if output.success && !output.timed_out && output_complete {
290 detect_zero_tests_matched(&output.stdout, &output.stderr, filtered)
291 } else {
292 ZeroTestDetection::default()
293 };
294 output.success = output.success && !output.timed_out && !detection.zero_tests_matched;
295 output.warning = if detection.zero_tests_matched {
296 Some(detection.reason.clone().unwrap_or_else(|| {
297 "0 tests matched; verify your test filter args because a 0-test pass proves nothing"
298 .to_string()
299 }))
300 } else if !output_complete {
301 Some("Output was truncated; aggregate and zero-test counts are unavailable. Use the output recovery information, when available, to inspect complete evidence.".to_string())
302 } else {
303 None
304 };
305 output.zero_tests_matched = detection.zero_tests_matched;
306 output.tests_executed = detection.tests_executed;
307 output.tests_filtered_out = detection.tests_filtered_out;
308 output.summary = output.warning.clone();
309 run_tests_result(output)
310 }
311
312 fn run_tests_result(result: RunTestsOutput) -> Result<ToolResult, ToolError> {
313 let mut tool_result =
314 ToolResult::json(&result).map_err(|e| ToolError::execution_failed(e.to_string()))?;
315 let mut metadata = serde_json::Map::new();
316 if let Some(summary) = summarize_cargo_failure(
317 &result.command,
318 &result.stdout,
319 &result.stderr,
320 result.exit_code,
321 ) {
322 metadata.insert("summary".to_string(), json!(summary.summary));
323 metadata.insert(
324 "cargo_failure_summary".to_string(),
325 summary.to_metadata_value(),
326 );
327 }
328 if result.zero_tests_matched {
329 metadata.insert("zero_tests_matched".to_string(), json!(true));
330 if let Some(executed) = result.tests_executed {
331 metadata.insert("tests_executed".to_string(), json!(executed));
332 }
333 if let Some(filtered_out) = result.tests_filtered_out {
334 metadata.insert("tests_filtered_out".to_string(), json!(filtered_out));
335 }
336 if let Some(warning) = result.warning.as_ref()
337 && !metadata.contains_key("summary")
338 {
339 metadata.insert("summary".to_string(), json!(warning));
340 }
341 }
342 if !metadata.is_empty() {
343 tool_result = tool_result.with_metadata(Value::Object(metadata));
344 }
345 Ok(tool_result)
346 }
347
348 fn spawn_cargo_in_shell_manager(
349 workspace: &Path,
350 args: &[String],
351 context: &ToolContext,
352 ) -> Result<String, ToolError> {
353 let Some(cargo) = codewhale_dependencies::Cargo::resolve() else {
354 return Err(ToolError::not_available(
355 "cargo is not installed or not in PATH",
356 ));
357 };
358 spawn_runner_job(
359 &cargo,
360 args,
361 workspace,
362 HashMap::new(),
363 format!("cargo {}", args.join(" ")),
364 context,
365 )
366 }
367
368 pub(super) fn spawn_runner_job(
369 program: &str,
370 args: &[String],
371 cwd: &Path,
372 mut env: HashMap<String, String>,
373 description: String,
374 context: &ToolContext,
375 ) -> Result<String, ToolError> {
376 if context.sandbox_backend.is_some() {
377 return Err(ToolError::not_available(
378 "this tool starts a local process, and this session runs commands in an external sandbox; run the command through the shell tool instead",
379 ));
380 }
381 let command = format!("{program} {args:?}");
382 let cwd = cwd.display().to_string();
383 crate::tools::shell::insert_agent_mark_env(&mut env, context);
384 let mut manager = context
385 .shell_manager
386 .lock()
387 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
388 let spawned = manager
389 .execute_with_options_env_for_owner_and_work(
390 &command,
391 Some((program, args)),
392 Some(&cwd),
393 BACKGROUND_JOB_TIMEOUT_MS,
394 true,
395 None,
396 false,
397 context.elevated_sandbox_policy.clone(),
398 env,
399 super::shell::shell_job_owner_from_context(context),
400 context.state_namespace.clone(),
401 context.origin_tool_call_id.clone(),
402 context.origin_turn_id.clone(),
403 super::shell::shell_work_lifecycle_from_context(context),
404 None,
405 false,
406 (1_000, BACKGROUND_JOB_TIMEOUT_MS),
407 )
408 .map_err(|err| {
409 if err.downcast_ref::<ShellLaunchNotStarted>().is_some() {
410 ToolError::not_available(err.to_string())
411 } else if err.chain().any(|cause| {
412 cause
413 .downcast_ref::<std::io::Error>()
414 .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound)
415 }) {
416 ToolError::not_available(format!("{program} is not installed or not in PATH"))
417 } else {
418 ToolError::execution_failed(format!("Failed to start {program}: {err:#}"))
419 }
420 })?;
421 let task_id = spawned.task_id.ok_or_else(|| {
422 ToolError::execution_failed(format!("{program} did not return a task_id"))
423 })?;
424 let _ = manager.write_stdin(&task_id, "", true);
425 let _ = manager.tag_description(&task_id, Some(description));
426 if let Some(active_task_id) = context.runtime.active_task_id.clone() {
427 let _ = manager.tag_linked_task(&task_id, Some(active_task_id));
428 }
429 Ok(task_id)
430 }
431
432 pub(super) fn background_job_metadata(
433 context: &ToolContext,
434 task_ids: &[String],
435 detached_start: bool,
436 ) -> Value {
437 let child_owned = context.owner_agent_id.is_some();
438 json!({
439 "backgrounded": true,
440 "detached_start": detached_start,
441 "task_ids": task_ids,
442 "auto_resume_on_completion": !child_owned,
443 "completion_surface": if child_owned {
444 "task_status_and_explicit_wait"
445 } else {
446 "runtime_event_and_task_status"
447 },
448 "background_policy": "nonblocking",
449 "poll_with": ["task_shell_wait"],
450 })
451 }
452
453 fn background_tests_tool_result(
454 output: RunTestsOutput,
455 context: &ToolContext,
456 detached_start: bool,
457 ) -> Result<ToolResult, ToolError> {
458 let task_ids: Vec<String> = output.task_id.clone().into_iter().collect();
459 let mut metadata = background_job_metadata(context, &task_ids, detached_start);
460 metadata["task_id"] = json!(output.task_id);
461 let tool_result =
462 ToolResult::json(&output).map_err(|e| ToolError::execution_failed(e.to_string()))?;
463 Ok(tool_result.with_metadata(metadata))
464 }
465
466 fn start_background_cargo(
467 workspace: &Path,
468 args: &[String],
469 command_str: &str,
470 context: &ToolContext,
471 ) -> Result<ToolResult, ToolError> {
472 let task_id = spawn_cargo_in_shell_manager(workspace, args, context)?;
473 let summary = format!(
474 "Started cargo test in the background (task_id: {task_id}). Call `task_shell_wait` with this task_id to read output, wait for completion, or cancel."
475 );
476 background_tests_tool_result(
477 RunTestsOutput {
478 capture: None,
479 success: true,
480 exit_code: None,
481 stdout: String::new(),
482 stderr: String::new(),
483 command: command_str.to_string(),
484 timed_out: false,
485 backgrounded: true,
486 status: Some("running".to_string()),
487 task_id: Some(task_id),
488 last_output_age_ms: None,
489 progress: None,
490 zero_tests_matched: false,
491 tests_executed: None,
492 tests_filtered_out: None,
493 warning: None,
494 summary: Some(summary),
495 },
496 context,
497 true,
498 )
499 }
500
501 pub(super) struct ForegroundJobGuard {
502 manager: SharedShellManager,
503 task_ids: Vec<String>,
504 }
505
506 impl ForegroundJobGuard {
507 pub(super) fn new(context: &ToolContext) -> Self {
508 Self {
509 manager: context.shell_manager.clone(),
510 task_ids: Vec::new(),
511 }
512 }
513
514 pub(super) fn track(&mut self, task_id: String) {
515 self.task_ids.push(task_id);
516 }
517
518 pub(super) fn hand_over(mut self) {
519 self.task_ids.clear();
520 }
521
522 pub(super) async fn cancel(self) -> Result<(), ToolError> {
523 tokio::task::spawn_blocking(move || self.cancel_blocking())
524 .await
525 .map_err(|err| ToolError::execution_failed(err.to_string()))?
526 }
527
528 fn cancel_blocking(mut self) -> Result<(), ToolError> {
529 let mut manager = self
530 .manager
531 .lock()
532 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
533 cancel_runner_jobs(&mut manager, &self.task_ids);
534 drop(manager);
535 self.task_ids.clear();
536 Ok(())
537 }
538
539 pub(super) async fn wait_unless_cancelled(
540 &self,
541 cancel_token: Option<&tokio_util::sync::CancellationToken>,
542 wait: Duration,
543 ) -> Result<bool, ToolError> {
544 let deadline = Instant::now() + wait;
545 let mut poll_ms = FOREGROUND_POLL_INITIAL_MS;
546 loop {
547 if cancel_token.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
548 return Ok(false);
549 }
550
551 let manager = self.manager.clone();
552 let task_ids = self.task_ids.clone();
553 let running = tokio::task::spawn_blocking(move || {
554 let mut manager = manager
555 .lock()
556 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
557 let mut running = false;
558 for task_id in &task_ids {
559 let status = manager
560 .poll_status(task_id)
561 .map_err(|err| ToolError::execution_failed(err.to_string()))?;
562 running |= status == ShellStatus::Running;
563 }
564 Ok::<_, ToolError>(running)
565 })
566 .await
567 .map_err(|err| ToolError::execution_failed(err.to_string()))??;
568
569 let remaining = deadline.saturating_duration_since(Instant::now());
570 if !running || remaining.is_zero() {
571 return Ok(true);
572 }
573 tokio::time::sleep(remaining.min(Duration::from_millis(poll_ms))).await;
574 poll_ms = (poll_ms * 2).min(FOREGROUND_POLL_MAX_MS);
575 }
576 }
577 }
578
579 impl Drop for ForegroundJobGuard {
580 fn drop(&mut self) {
581 if self.task_ids.is_empty() {
582 return;
583 }
584 let manager = self.manager.clone();
585 let task_ids = std::mem::take(&mut self.task_ids);
586 let cleanup = move || {
587 let mut manager = manager
588 .lock()
589 .unwrap_or_else(std::sync::PoisonError::into_inner);
590 cancel_runner_jobs(&mut manager, &task_ids);
591 };
592 if let Ok(runtime) = tokio::runtime::Handle::try_current() {
593 runtime.spawn_blocking(cleanup);
594 } else {
595 cleanup();
596 }
597 }
598 }
599
600 fn cancel_runner_jobs(manager: &mut ShellManager, task_ids: &[String]) {
601 for task_id in task_ids {
602 if let Ok(killed) = manager.kill(task_id) {
603 manager.mark_cancel_reported(&killed);
604 }
605 }
606 }
607
608 async fn run_cargo_with_auto_background(
609 workspace: &Path,
610 args: &[String],
611 command_str: &str,
612 context: &ToolContext,
613 foreground_wait: Duration,
614 filtered: bool,
615 ) -> Result<ToolResult, ToolError> {
616 let task_id = spawn_cargo_in_shell_manager(workspace, args, context)?;
617 let mut guard = ForegroundJobGuard::new(context);
618 guard.track(task_id.clone());
619 if !guard
620 .wait_unless_cancelled(context.cancel_token.as_ref(), foreground_wait)
621 .await?
622 {
623 guard.cancel().await?;
624 return Err(ToolError::cancelled("cargo test cancelled"));
625 }
626 guard.hand_over();
627
628 let manager = context.shell_manager.clone();
629 let output_task_id = task_id.clone();
630 let session_id = context.state_namespace.clone();
631 let (snapshot, metadata, last_output_age_ms, progress) =
632 tokio::task::spawn_blocking(move || {
633 let mut manager = manager
634 .lock()
635 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
636 let (snapshot, metadata) = manager
637 .test_output(&output_task_id, &session_id)
638 .map_err(|err| ToolError::execution_failed(format!(
639 "Failed to collect test output for task_id={output_task_id}: {err}; output remains available for retry with task_shell_wait"
640 )))?;
641 let age = manager.last_output_age_ms(&output_task_id);
642 let progress = manager.running_progress(&output_task_id);
643 Ok::<_, ToolError>((snapshot, metadata, age, progress))
644 })
645 .await
646 .map_err(|err| ToolError::execution_failed(err.to_string()))??;
647 let capture = TestCapture::from(&snapshot);
648 if snapshot.status != ShellStatus::Running {
649 let mut result = finish_completed_tests(
650 RunTestsOutput {
651 success: snapshot.status == ShellStatus::Completed && snapshot.exit_code == Some(0),
652 exit_code: Some(
653 snapshot
654 .exit_code
655 .and_then(|code| i32::try_from(code).ok())
656 .unwrap_or(-1),
657 ),
658 stdout: snapshot.stdout,
659 stderr: snapshot.stderr,
660 command: command_str.to_string(),
661 timed_out: snapshot.status == ShellStatus::TimedOut,
662 capture: Some(capture),
663 ..Default::default()
664 },
665 filtered,
666 )?;
667 result
668 .metadata
669 .get_or_insert_with(|| json!({}))
670 .as_object_mut()
671 .unwrap()
672 .extend(metadata.as_object().unwrap().clone());
673 context
674 .shell_manager
675 .lock()
676 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?
677 .acknowledge_foreground_completion(&task_id);
678 return Ok(result);
679 }
680 let summary = format!(
681 "cargo test is still running after {}ms and moved to the background (task_id: {task_id}). Call `task_shell_wait` with this task_id to read output, wait for completion, or cancel.",
682 foreground_wait.as_millis()
683 );
684 background_tests_tool_result(
685 RunTestsOutput {
686 capture: Some(capture),
687 success: true,
688 exit_code: None,
689 stdout: snapshot.stdout,
690 stderr: snapshot.stderr,
691 command: command_str.to_string(),
692 timed_out: false,
693 backgrounded: true,
694 status: Some("running".to_string()),
695 task_id: Some(task_id),
696 last_output_age_ms,
697 progress,
698 zero_tests_matched: false,
699 tests_executed: None,
700 tests_filtered_out: None,
701 warning: None,
702 summary: Some(summary),
703 },
704 context,
705 false,
706 )
707 }
708
709 pub(crate) fn has_test_filter_args(extra_tokens: &[String]) -> bool {
710 const FLAGS_WITH_VALUE: &[&str] = &[
711 "-p",
712 "--package",
713 "--bin",
714 "--example",
715 "--test",
716 "--bench",
717 "--features",
718 "-F",
719 "--target",
720 "--profile",
721 "-j",
722 "--jobs",
723 "--color",
724 "--message-format",
725 "--manifest-path",
726 "--target-dir",
727 "--config",
728 ];
729 let mut after_sep = false;
730 let mut skip_next = false;
731 for token in extra_tokens {
732 if skip_next {
733 skip_next = false;
734 continue;
735 }
736 if !after_sep && token == "--" {
737 after_sep = true;
738 continue;
739 }
740 if after_sep {
741 if !token.starts_with('-') || matches!(token.as_str(), "--exact" | "--ignored") {
742 return true;
743 }
744 continue;
745 }
746 if token == "--test" || token.starts_with("--test=") {
747 return true;
748 }
749 if token.starts_with('-') {
750 if !token.contains('=') && FLAGS_WITH_VALUE.contains(&token.as_str()) {
751 skip_next = true;
752 }
753 continue;
754 }
755 return true;
756 }
757 false
758 }
759
760 fn parse_libtest_summary_line(line: &str) -> Option<(usize, usize, usize, usize, Option<usize>)> {
761 let rest = line.trim().strip_prefix("test result:")?;
762 let (_, counts) = rest.split_once('.')?;
763 let mut passed = None;
764 let mut failed = None;
765 let mut ignored = 0usize;
766 let mut measured = 0usize;
767 let mut filtered_out = None;
768 for part in counts.split(';') {
769 let part = part.trim();
770 if let Some(n) = part
771 .strip_suffix(" passed")
772 .and_then(|v| v.trim().parse::<usize>().ok())
773 {
774 passed = Some(n);
775 } else if let Some(n) = part
776 .strip_suffix(" failed")
777 .and_then(|v| v.trim().parse::<usize>().ok())
778 {
779 failed = Some(n);
780 } else if let Some(n) = part
781 .strip_suffix(" ignored")
782 .and_then(|v| v.trim().parse::<usize>().ok())
783 {
784 ignored = n;
785 } else if let Some(n) = part
786 .strip_suffix(" measured")
787 .and_then(|v| v.trim().parse::<usize>().ok())
788 {
789 measured = n;
790 } else if let Some(n) = part
791 .strip_suffix(" filtered out")
792 .and_then(|v| v.trim().parse::<usize>().ok())
793 {
794 filtered_out = Some(n);
795 }
796 }
797 Some((passed?, failed?, ignored, measured, filtered_out))
798 }
799
800 fn parse_number_before(haystack: &str, suffix: &str) -> Option<usize> {
801 let idx = haystack.find(suffix)?;
802 let prefix = haystack[..idx].trim_end();
803 let token = prefix
804 .rsplit(|c: char| !c.is_ascii_digit())
805 .next()
806 .filter(|s| !s.is_empty())?;
807 token.parse::<usize>().ok()
808 }
809
810 fn normalize_ascii_spaces(text: &str) -> String {
811 text.split_whitespace().collect::<Vec<_>>().join(" ")
812 }
813
814 fn line_has_positive_pass_or_fail(lower_norm: &str) -> bool {
815 parse_number_before(lower_norm, " passed").is_some_and(|n| n > 0)
816 || parse_number_before(lower_norm, " failed").is_some_and(|n| n > 0)
817 }
818
819 pub(crate) fn detect_zero_tests_matched(
820 stdout: &str,
821 stderr: &str,
822 filtered: bool,
823 ) -> ZeroTestDetection {
824 let mut clean_stdout = String::with_capacity(stdout.len());
825 let mut clean_stderr = String::with_capacity(stderr.len());
826 codewhale_sanitize::sanitize::strip_ansi_into(stdout, &mut clean_stdout);
827 codewhale_sanitize::sanitize::strip_ansi_into(stderr, &mut clean_stderr);
828
829 let all_lines: Vec<&str> = clean_stdout.lines().chain(clean_stderr.lines()).collect();
830
831 let mut libtest_lines = 0usize;
832 let mut libtest_passed = 0usize;
833 let mut libtest_failed = 0usize;
834 let mut libtest_ignored = 0usize;
835 let mut libtest_measured = 0usize;
836 let mut libtest_filtered = 0usize;
837 let mut saw_filtered_field = false;
838 for line in &all_lines {
839 if let Some((passed, failed, ignored, measured, filtered_out)) =
840 parse_libtest_summary_line(line)
841 {
842 libtest_lines += 1;
843 libtest_passed = libtest_passed.saturating_add(passed);
844 libtest_failed = libtest_failed.saturating_add(failed);
845 libtest_ignored = libtest_ignored.saturating_add(ignored);
846 libtest_measured = libtest_measured.saturating_add(measured);
847 if let Some(fo) = filtered_out {
848 saw_filtered_field = true;
849 libtest_filtered = libtest_filtered.saturating_add(fo);
850 }
851 }
852 }
853 if libtest_lines > 0 {
854 let executed = libtest_passed
855 .saturating_add(libtest_failed)
856 .saturating_add(libtest_measured);
857 let filtered_out = saw_filtered_field.then_some(libtest_filtered);
858 if executed == 0 && libtest_failed == 0 && (libtest_filtered > 0 || filtered) {
859 return ZeroTestDetection {
860 zero_tests_matched: true,
861 tests_executed: Some(0),
862 tests_filtered_out: filtered_out,
863 runner: Some("cargo"),
864 reason: Some(format!(
865 "0 tests executed ({libtest_filtered} filtered out, {libtest_ignored} ignored); check your test filter — a 0-test pass proves nothing"
866 )),
867 };
868 }
869 return ZeroTestDetection {
870 zero_tests_matched: false,
871 tests_executed: Some(executed),
872 tests_filtered_out: filtered_out,
873 runner: Some("cargo"),
874 reason: None,
875 };
876 }
877
878 let mut saw_nextest = false;
879 let mut nextest_run = 0usize;
880 let mut nextest_skipped = None;
881 for line in &all_lines {
882 let trimmed = line.trim();
883 if trimmed.contains("Summary [")
884 && let Some(n) = parse_number_before(trimmed, " tests run")
885 .or_else(|| parse_number_before(trimmed, " test run"))
886 {
887 saw_nextest = true;
888 nextest_run = nextest_run.saturating_add(n);
889 if let Some(sk) = parse_number_before(trimmed, " skipped") {
890 nextest_skipped = Some(nextest_skipped.unwrap_or(0usize).saturating_add(sk));
891 }
892 } else if trimmed.starts_with("Starting 0 tests across")
893 || trimmed.eq_ignore_ascii_case("error: no tests to run")
894 {
895 saw_nextest = true;
896 if let Some(sk) = parse_number_before(trimmed, " skipped") {
897 nextest_skipped = Some(nextest_skipped.unwrap_or(0usize).saturating_add(sk));
898 }
899 }
900 }
901 if saw_nextest {
902 if nextest_run == 0 {
903 return ZeroTestDetection {
904 zero_tests_matched: true,
905 tests_executed: Some(0),
906 tests_filtered_out: nextest_skipped,
907 runner: Some("nextest"),
908 reason: Some(
909 "nextest executed 0 tests; check your test filter — a 0-test run proves nothing"
910 .to_string(),
911 ),
912 };
913 }
914 return ZeroTestDetection {
915 zero_tests_matched: false,
916 tests_executed: Some(nextest_run),
917 tests_filtered_out: nextest_skipped,
918 runner: Some("nextest"),
919 reason: None,
920 };
921 }
922
923 let mut any_positive = false;
924 let mut saw_go_pass_or_fail = false;
925 let mut pytest_zero = false;
926 let mut pytest_deselected = None;
927 let mut js_zero = false;
928 let mut go_zero = false;
929
930 for line in &all_lines {
931 let trimmed = line.trim();
932 if trimmed.starts_with("--- PASS:") || trimmed.starts_with("--- FAIL:") {
933 saw_go_pass_or_fail = true;
934 any_positive = true;
935 }
936 let lower_norm = normalize_ascii_spaces(&trimmed.to_ascii_lowercase());
937 if line_has_positive_pass_or_fail(&lower_norm) {
938 any_positive = true;
939 }
940 if lower_norm.contains("collected 0 items")
941 || lower_norm.contains("no tests ran in ")
942 || (lower_norm.contains("deselected") && lower_norm.contains("0 selected"))
943 {
944 pytest_zero = true;
945 if let Some(d) = parse_number_before(&lower_norm, " deselected") {
946 pytest_deselected = Some(d);
947 }
948 }
949 if lower_norm.contains("no tests found")
950 || lower_norm.contains("no test files found")
951 || lower_norm.contains("tests: 0 total")
952 || lower_norm.contains("0 tests passed")
953 || lower_norm == "tests 0 passed"
954 || lower_norm == "test files 0 passed"
955 {
956 js_zero = true;
957 }
958 if lower_norm.contains("testing: warning: no tests to run") {
959 go_zero = true;
960 }
961 }
962
963 if pytest_zero && !any_positive {
964 return ZeroTestDetection {
965 zero_tests_matched: true,
966 tests_executed: Some(0),
967 tests_filtered_out: pytest_deselected,
968 runner: Some("pytest"),
969 reason: Some(
970 "pytest collected/selected 0 tests; check your test filter — a 0-test run proves nothing"
971 .to_string(),
972 ),
973 };
974 }
975 if js_zero && !any_positive {
976 return ZeroTestDetection {
977 zero_tests_matched: true,
978 tests_executed: Some(0),
979 tests_filtered_out: None,
980 runner: Some("jest/vitest"),
981 reason: Some(
982 "test runner found 0 matching tests; check your test filter — a 0-test run proves nothing"
983 .to_string(),
984 ),
985 };
986 }
987 if go_zero && !saw_go_pass_or_fail {
988 return ZeroTestDetection {
989 zero_tests_matched: true,
990 tests_executed: Some(0),
991 tests_filtered_out: None,
992 runner: Some("go test"),
993 reason: Some(
994 "go test reported no tests to run; check your -run filter — a 0-test run proves nothing"
995 .to_string(),
996 ),
997 };
998 }
999
1000 ZeroTestDetection::default()
1001 }
1002
1003 // === Helpers ===
1004
1005 /// Ceiling for one `cargo test` run. Long suites fit; a hung test does not
1006 /// hold the turn forever.
1007 const RUN_TESTS_TIMEOUT: Duration = Duration::from_secs(30 * 60);
1008
1009 /// Run cargo without blocking a runtime worker. Stop and the timeout both end
1010 /// the whole process tree (cargo and the test binaries it started). A timeout
1011 /// still returns the output written so far (`stopped`): it is the only
1012 /// evidence of which test hung.
1013 async fn run_cargo(
1014 workspace: &Path,
1015 args: &[String],
1016 context: &ToolContext,
1017 timeout: Duration,
1018 ) -> Result<codewhale_runtime::process_tree::ContainedOutput, ToolError> {
1019 let Some(cargo) = codewhale_dependencies::Cargo::resolve() else {
1020 return Err(ToolError::not_available(
1021 "cargo is not installed or not in PATH",
1022 ));
1023 };
1024 // `cargo test` builds and runs workspace code: it starts like an
1025 // `exec_shell` command, inside this session's sandbox and without parent
1026 // credentials.
1027 let mut cmd = crate::tools::shell::sandboxed_runner_command(
1028 context,
1029 &cargo,
1030 args.to_vec(),
1031 workspace,
1032 timeout,
1033 )?;
1034 let run = codewhale_runtime::process_tree::contained_output_until(
1035 &mut cmd,
1036 tokio::time::sleep(timeout),
1037 );
1038 let cancelled = async {
1039 match context.cancel_token.as_ref() {
1040 Some(token) => token.cancelled().await,
1041 None => std::future::pending::<()>().await,
1042 }
1043 };
1044 // Dropping `run` on cancel kills the tree.
1045 let output = tokio::select! {
1046 output = run => output,
1047 () = cancelled => return Err(ToolError::cancelled("cargo test cancelled")),
1048 };
1049 output.map_err(|e| {
1050 if e.kind() == std::io::ErrorKind::NotFound {
1051 ToolError::not_available("cargo is not installed or not in PATH")
1052 } else {
1053 ToolError::execution_failed(format!("Failed to run cargo: {e}"))
1054 }
1055 })
1056 }
1057
1058 fn format_command(workspace: &Path, args: &[String]) -> String {
1059 format!(
1060 "(cd {} && cargo {})",
1061 workspace.display(),
1062 args.iter()
1063 .map(String::as_str)
1064 .collect::<Vec<_>>()
1065 .join(" ")
1066 )
1067 }
1068
1069 #[cfg(test)]
1070 mod tests {
1071 use super::*;
1072 use std::fs;
1073 use std::process::Command;
1074 use std::sync::atomic::{AtomicU64, Ordering};
1075 use tempfile::tempdir;
1076
1077 static NEXT_CARGO_PROJECT: AtomicU64 = AtomicU64::new(0);
1078
1079 fn cargo_available() -> bool {
1080 Command::new("cargo")
1081 .arg("--version")
1082 .output()
1083 .map(|o| o.status.success())
1084 .unwrap_or(false)
1085 }
1086
1087 fn init_cargo_project(root: &Path) -> std::path::PathBuf {
1088 let project_dir = root.join("project");
1089 let package_name = format!(
1090 "eval_project_{}_{}",
1091 std::process::id(),
1092 NEXT_CARGO_PROJECT.fetch_add(1, Ordering::Relaxed)
1093 );
1094 fs::create_dir_all(&project_dir).expect("create project dir");
1095 let status = codewhale_dependencies::Cargo::command()
1096 .expect("cargo not found")
1097 .args(["init", "--lib", "--vcs", "none", "-q"])
1098 .arg("--name")
1099 .arg(package_name)
1100 .current_dir(&project_dir)
1101 .status()
1102 .expect("cargo should spawn");
1103 assert!(status.success(), "cargo init failed");
1104 project_dir
1105 }
1106
1107 /// `run_tests` is `ToolCapability::ExecutesCode`, so it must follow the
1108 /// explicit-approval policy that applies to other code-executing tools.
1109 #[test]
1110 fn run_tests_requires_user_approval() {
1111 let tool = RunTestsTool;
1112 assert_eq!(
1113 tool.approval_requirement(),
1114 ApprovalRequirement::Required,
1115 "run_tests must gate cargo test behind user approval"
1116 );
1117 }
1118
1119 /// Stop must reach `cargo test`: the call returns as cancelled instead of
1120 /// blocking a runtime worker until cargo exits on its own.
1121 #[tokio::test]
1122 async fn run_tests_honors_cancellation() {
1123 if !cargo_available() {
1124 return;
1125 }
1126 let tmp = tempdir().expect("tempdir");
1127 let token = tokio_util::sync::CancellationToken::new();
1128 token.cancel();
1129 let ctx = ToolContext::new(tmp.path()).with_cancel_token(token);
1130 let result = RunTestsTool.execute(json!({}), &ctx).await;
1131 assert!(
1132 matches!(result, Err(ToolError::Cancelled { .. })),
1133 "cancelled run_tests must not run to completion: {result:?}"
1134 );
1135 }
1136
1137 #[tokio::test]
1138 async fn run_tests_succeeds_on_fresh_project() {
1139 if !cargo_available() {
1140 return;
1141 }
1142 let tmp = tempdir().expect("tempdir");
1143 // Release jobs commonly export one CARGO_TARGET_DIR for the whole
1144 // workspace. Give concurrent nested Cargo fixtures distinct package
1145 // identities so their test artifacts cannot replace each other.
1146 let project_dir = init_cargo_project(tmp.path());
1147
1148 let ctx = ToolContext::new(&project_dir);
1149 let tool = RunTestsTool;
1150 let result = tool.execute(json!({}), &ctx).await.expect("execute");
1151 assert!(result.success);
1152
1153 let parsed: RunTestsOutput =
1154 serde_json::from_str(&result.content).expect("tool result should be json");
1155 assert!(
1156 parsed.success,
1157 "nested cargo test unexpectedly failed:\n{}",
1158 parsed.stderr
1159 );
1160 assert_eq!(parsed.exit_code, Some(0));
1161 assert_eq!(parsed.tests_executed, Some(1));
1162 assert!(parsed.capture.as_ref().unwrap().output_complete);
1163 assert!(parsed.command.contains("cargo test"));
1164 }
1165
1166 #[test]
1167 fn run_tests_foreground_spill_preserves_evidence_without_partial_counts() {
1168 use crate::tools::tool_result_retrieval::RetrieveToolResultTool;
1169
1170 assert!(cargo_available(), "this regression requires Cargo");
1171 let _artifact_lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
1172 .lock()
1173 .unwrap_or_else(|error| error.into_inner());
1174 tokio::runtime::Builder::new_current_thread()
1175 .enable_all()
1176 .build()
1177 .unwrap()
1178 .block_on(async {
1179 struct ArtifactRootReset(Option<std::path::PathBuf>);
1180 impl Drop for ArtifactRootReset {
1181 fn drop(&mut self) {
1182 codewhale_runtime::artifacts::set_test_artifact_sessions_root(
1183 self.0.take(),
1184 );
1185 }
1186 }
1187 let tmp = tempdir().unwrap();
1188 let _artifact_root = ArtifactRootReset(
1189 codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
1190 tmp.path().join("sessions"),
1191 )),
1192 );
1193 let project = init_cargo_project(tmp.path());
1194 fs::write(
1195 project.join("src/lib.rs"),
1196 r#"
1197 #[test]
1198 fn early() { println!("EARLY_TEST_EVIDENCE"); }
1199 "#,
1200 )
1201 .unwrap();
1202 fs::create_dir(project.join("tests")).unwrap();
1203 let manifest = fs::read_to_string(project.join("Cargo.toml")).unwrap();
1204 for late_test in [false, true] {
1205 let session = if late_test {
1206 "cargo-partial-count"
1207 } else {
1208 "cargo-false-zero"
1209 };
1210 let header = if late_test {
1211 "#[test] fn late()"
1212 } else {
1213 "fn main()"
1214 };
1215 fs::write(
1216 project.join("Cargo.toml"),
1217 format!(
1218 "{manifest}\n[[test]]\nname = \"verbose\"\nharness = {late_test}\n"
1219 ),
1220 )
1221 .unwrap();
1222 fs::write(
1223 project.join("tests/verbose.rs"),
1224 format!(
1225 r#"
1226 {header} {{
1227 use std::io::Write;
1228 let mut out = std::io::stdout().lock();
1229 let row = vec![b'x'; 1023];
1230 for i in 0..18_432 {{
1231 if i == 9_000 {{ writeln!(out, "MIDDLE_TEST_EVIDENCE").unwrap(); }}
1232 out.write_all(&row).unwrap();
1233 out.write_all(b"\n").unwrap();
1234 }}
1235 writeln!(out, "LAST_TEST_EVIDENCE").unwrap();
1236 }}
1237 "#
1238 ),
1239 )
1240 .unwrap();
1241 let ctx = ToolContext::new(&project)
1242 .with_state_namespace(session)
1243 .with_origin_tool_call_id("cargo-verbose");
1244 let result = RunTestsTool
1245 .execute(
1246 json!({
1247 "args": "--offline -- --nocapture --test-threads=1",
1248 "timeout_ms": 120_000
1249 }),
1250 &ctx,
1251 )
1252 .await
1253 .unwrap();
1254 let parsed: RunTestsOutput = serde_json::from_str(&result.content).unwrap();
1255 assert!(parsed.success, "{}", result.content);
1256 assert!(!parsed.backgrounded);
1257 assert!(!parsed.zero_tests_matched);
1258 assert_eq!(parsed.tests_executed, None);
1259 assert_eq!(parsed.tests_filtered_out, None);
1260 let capture = parsed.capture.unwrap();
1261 assert!(!capture.output_complete);
1262 assert!(capture.stdout_total_len > 16 * 1024 * 1024);
1263 assert!(capture.stdout_omitted > 16 * 1024 * 1024);
1264 assert!(parsed.stdout.contains("LAST_TEST_EVIDENCE"));
1265 assert!(result.content.len() < 64 * 1024);
1266 let metadata = result.metadata.unwrap();
1267 assert_eq!(metadata["artifact_session_id"], session);
1268 let artifact = metadata["artifact_id"]
1269 .as_str()
1270 .expect("test output artifact");
1271 for marker in [
1272 "EARLY_TEST_EVIDENCE",
1273 "MIDDLE_TEST_EVIDENCE",
1274 "LAST_TEST_EVIDENCE",
1275 ] {
1276 let recovered = RetrieveToolResultTool
1277 .execute(
1278 json!({
1279 "ref": artifact, "mode": "query", "query": marker
1280 }),
1281 &ctx,
1282 )
1283 .await
1284 .unwrap();
1285 assert!(recovered.success, "{}", recovered.content);
1286 let body: Value = serde_json::from_str(&recovered.content).unwrap();
1287 assert!(body["matched_lines"].as_u64().unwrap() > 0);
1288 assert!(body["matches_returned"].as_u64().unwrap() > 0);
1289 assert!(
1290 body["results"]
1291 .as_array()
1292 .unwrap()
1293 .iter()
1294 .any(|result| result["excerpt"].as_str().unwrap().contains(marker))
1295 );
1296 }
1297 let foreign = ctx.clone().with_state_namespace("cargo-foreign");
1298 let denied = RetrieveToolResultTool
1299 .execute(
1300 json!({
1301 "ref": artifact, "mode": "lines", "lines": "1-10"
1302 }),
1303 &foreign,
1304 )
1305 .await;
1306 assert!(denied.is_err() || denied.is_ok_and(|result| !result.success));
1307 assert!(
1308 !ctx.shell_manager
1309 .lock()
1310 .unwrap()
1311 .may_have_undelivered_completion_for_session(session)
1312 );
1313 }
1314 let session = "cargo-publication-retry";
1315 let blocked = tmp.path().join("sessions").join(session).join("artifacts");
1316 fs::create_dir_all(blocked.parent().unwrap()).unwrap();
1317 fs::write(&blocked, "publication blocked").unwrap();
1318 let ctx = ToolContext::new(&project)
1319 .with_state_namespace(session)
1320 .with_origin_tool_call_id("cargo-retry");
1321 let failed = RunTestsTool
1322 .execute(
1323 json!({
1324 "args": "--offline -- --nocapture --test-threads=1", "timeout_ms": 120_000
1325 }),
1326 &ctx,
1327 )
1328 .await;
1329 assert!(failed.is_err());
1330 assert!(
1331 ctx.shell_manager
1332 .lock()
1333 .unwrap()
1334 .has_finished_unreported_jobs_for_session(session)
1335 );
1336 fs::remove_file(&blocked).unwrap();
1337 let evidence = ctx
1338 .shell_manager
1339 .lock()
1340 .unwrap()
1341 .drain_finished_jobs_with_evidence_for_session(session);
1342 assert_eq!(evidence.len(), 1);
1343 let receipt: Value = serde_json::from_slice(&evidence[0].artifact_bytes()).unwrap();
1344 let artifact = receipt["stdout"]["artifact_id"]
1345 .as_str()
1346 .expect("recovered test artifact");
1347 let recovered = RetrieveToolResultTool
1348 .execute(
1349 json!({
1350 "ref": artifact, "mode": "query", "query": "EARLY_TEST_EVIDENCE"
1351 }),
1352 &ctx,
1353 )
1354 .await
1355 .unwrap();
1356 assert!(recovered.success);
1357 let body: Value = serde_json::from_str(&recovered.content).unwrap();
1358 assert!(body["matched_lines"].as_u64().unwrap() > 0);
1359 assert!(body["results"].as_array().unwrap().iter().any(|result| {
1360 result["excerpt"]
1361 .as_str()
1362 .unwrap()
1363 .contains("EARLY_TEST_EVIDENCE")
1364 }));
1365 });
1366 }
1367
1368 #[tokio::test]
1369 async fn run_tests_reports_failures_without_hard_error() {
1370 if !cargo_available() {
1371 return;
1372 }
1373 let tmp = tempdir().expect("tempdir");
1374 let project_dir = init_cargo_project(tmp.path());
1375
1376 let lib_rs = project_dir.join("src/lib.rs");
1377 let failing = r#"
1378 pub fn add(a: i32, b: i32) -> i32 { a + b }
1379
1380 #[cfg(test)]
1381 mod tests {
1382 #[test]
1383 fn fails() {
1384 assert_eq!(2 + 2, 5);
1385 }
1386 }
1387 "#;
1388 fs::write(&lib_rs, failing).expect("write failing test");
1389
1390 let ctx = ToolContext::new(&project_dir);
1391 let tool = RunTestsTool;
1392 let result = tool.execute(json!({}), &ctx).await.expect("execute");
1393 assert!(result.success);
1394
1395 let parsed: RunTestsOutput =
1396 serde_json::from_str(&result.content).expect("tool result should be json");
1397 assert!(
1398 !parsed.success,
1399 "nested cargo test unexpectedly passed:\nstdout:\n{}\nstderr:\n{}",
1400 parsed.stdout, parsed.stderr
1401 );
1402 assert!(parsed.exit_code.is_some_and(|code| code != 0));
1403 let metadata = result.metadata.expect("metadata");
1404 assert_eq!(
1405 metadata["cargo_failure_summary"]["kind"],
1406 json!("test_failure")
1407 );
1408 assert!(
1409 metadata["cargo_failure_summary"]["summary"]
1410 .as_str()
1411 .unwrap()
1412 .contains("Failing tests:")
1413 );
1414 }
1415
1416 #[test]
1417 fn long_failing_output_comes_back_whole_and_the_summary_sees_its_end() {
1418 // #6508: stdout used to be cut at 40,000 characters, so the model
1419 // read passing tests and never saw which one failed, and the failure
1420 // summary ran on the truncated text.
1421 let stdout = format!(
1422 "{}test tools::git::tests::diff_keeps_the_last_file ... FAILED\n\ntest result: FAILED. 3000 passed; 1 failed; 0 ignored",
1423 "test tools::ok ... ok\n".repeat(3_000)
1424 );
1425 assert!(stdout.chars().count() > 40_000);
1426 let result = run_tests_result(RunTestsOutput {
1427 success: false,
1428 exit_code: Some(101),
1429 stdout: stdout.clone(),
1430 stderr: String::new(),
1431 command: "(cd /repo && cargo test)".to_string(),
1432 timed_out: false,
1433 ..RunTestsOutput::default()
1434 })
1435 .expect("result");
1436
1437 let parsed: Value = serde_json::from_str(&result.content).expect("json");
1438 assert_eq!(parsed["stdout"], json!(stdout));
1439 let summary = result
1440 .metadata
1441 .as_ref()
1442 .and_then(|metadata| metadata.get("summary"))
1443 .and_then(Value::as_str)
1444 .expect("failure summary");
1445 assert!(
1446 summary.contains("diff_keeps_the_last_file"),
1447 "summary: {summary}"
1448 );
1449 }
1450
1451 /// A child parked at a workspace root that is not the project root (the
1452 /// #6296 verifier) runs the suite where the manifest lives instead of
1453 /// failing on cwd.
1454 #[tokio::test]
1455 async fn run_tests_cwd_scopes_cargo_to_subdir() {
1456 if !cargo_available() {
1457 return;
1458 }
1459 let tmp = tempdir().expect("tempdir");
1460 let project_dir = init_cargo_project(tmp.path());
1461
1462 let ctx = ToolContext::new(tmp.path());
1463 let result = RunTestsTool
1464 .execute(json!({"cwd": "project"}), &ctx)
1465 .await
1466 .expect("cwd-scoped execute");
1467 assert!(result.success);
1468
1469 let parsed: RunTestsOutput =
1470 serde_json::from_str(&result.content).expect("tool result should be json");
1471 assert!(
1472 parsed.success,
1473 "nested cargo test unexpectedly failed:\\n{}",
1474 parsed.stderr
1475 );
1476 // `resolve_existing_dir` returns the canonical path, which on Windows
1477 // carries the `\\?\` verbatim prefix the raw tempdir lacks (#6346).
1478 let scoped_dir = project_dir.canonicalize().expect("canonical project dir");
1479 assert!(
1480 parsed.command.contains(&scoped_dir.display().to_string()),
1481 "cargo must run in the scoped dir, ran: {}",
1482 parsed.command
1483 );
1484 }
1485
1486 #[tokio::test]
1487 async fn run_tests_cwd_fails_closed_with_a_named_fallback() {
1488 let tmp = tempdir().expect("tempdir");
1489 let ctx = ToolContext::new(tmp.path());
1490
1491 let escape = RunTestsTool
1492 .execute(json!({"cwd": "../escape"}), &ctx)
1493 .await
1494 .expect_err("workspace escape must be refused");
1495 assert!(escape.to_string().contains("escapes workspace"), "{escape}");
1496
1497 let missing = RunTestsTool
1498 .execute(json!({"cwd": "no-such-dir"}), &ctx)
1499 .await
1500 .expect_err("missing dir must be refused");
1501 let message = missing.to_string();
1502 assert!(message.contains("not an existing directory"), "{message}");
1503 assert!(message.contains("drop `cwd`"), "{message}");
1504 }
1505
1506 #[cfg(unix)]
1507 #[tokio::test]
1508 async fn run_cargo_does_not_inherit_parent_secret_env() {
1509 use crate::test_support::{EnvVarGuard, lock_test_env};
1510 use std::os::unix::fs::PermissionsExt;
1511 if !cargo_available() {
1512 return;
1513 }
1514 let _env_lock = lock_test_env();
1515 let bin = tempdir().expect("bin dir");
1516 // cargo resolves `cargo envprobe` to a `cargo-envprobe` on PATH, which
1517 // lets the test observe the environment cargo hands its children.
1518 let probe = bin.path().join("cargo-envprobe");
1519 fs::write(
1520 &probe,
1521 "#!/bin/sh\nprintf 'secret=%s target=%s' \"${CODEWHALE_TEST_CARGO_SECRET-unset}\" \"${CARGO_TARGET_DIR-unset}\"\n",
1522 )
1523 .expect("write probe");
1524 fs::set_permissions(&probe, fs::Permissions::from_mode(0o755)).expect("chmod probe");
1525 let path = std::env::var_os("PATH").unwrap_or_default();
1526 let mut paths = vec![bin.path().to_path_buf()];
1527 paths.extend(std::env::split_paths(&path));
1528 let _path = EnvVarGuard::set("PATH", std::env::join_paths(paths).expect("join PATH"));
1529 let _secret = EnvVarGuard::set("CODEWHALE_TEST_CARGO_SECRET", "cargo-secret-value");
1530 // Non-secret build configuration still reaches cargo.
1531 let _target = EnvVarGuard::set("CARGO_TARGET_DIR", "/tmp/codewhale-fixture-target");
1532 let workspace = tempdir().expect("workspace");
1533
1534 let ctx = ToolContext::new(workspace.path());
1535 let run = run_cargo(
1536 workspace.path(),
1537 &["envprobe".to_string()],
1538 &ctx,
1539 RUN_TESTS_TIMEOUT,
1540 )
1541 .await
1542 .expect("cargo runs");
1543 assert!(!run.stopped);
1544 let output = run.output;
1545 let stdout = String::from_utf8_lossy(&output.stdout);
1546 assert!(
1547 output.status.success(),
1548 "{stdout} {}",
1549 String::from_utf8_lossy(&output.stderr)
1550 );
1551 assert_eq!(
1552 stdout.trim(),
1553 "secret=unset target=/tmp/codewhale-fixture-target"
1554 );
1555 }
1556
1557 /// A run that hits the timeout is killed, tree and all, and still returns
1558 /// what it wrote: the only evidence of which test hung.
1559 #[cfg(unix)]
1560 #[tokio::test]
1561 async fn timed_out_run_cargo_keeps_partial_output_and_kills_the_tree() {
1562 use crate::test_support::{EnvVarGuard, lock_test_env};
1563 use std::os::unix::fs::PermissionsExt;
1564 if !cargo_available() {
1565 return;
1566 }
1567 let _env_lock = lock_test_env();
1568 let bin = tempdir().expect("bin dir");
1569 let probe = bin.path().join("cargo-hangprobe");
1570 fs::write(
1571 &probe,
1572 "#!/bin/sh\necho 'test slow_case ... started'\nsleep 300 &\necho $! > hang.pid\nwait\n",
1573 )
1574 .expect("write probe");
1575 fs::set_permissions(&probe, fs::Permissions::from_mode(0o755)).expect("chmod probe");
1576 let path = std::env::var_os("PATH").unwrap_or_default();
1577 let mut paths = vec![bin.path().to_path_buf()];
1578 paths.extend(std::env::split_paths(&path));
1579 let _path = EnvVarGuard::set("PATH", std::env::join_paths(paths).expect("join PATH"));
1580 let workspace = tempdir().expect("workspace");
1581 let pid_file = workspace.path().join("hang.pid");
1582
1583 let ctx = ToolContext::new(workspace.path());
1584 let run = run_cargo(
1585 workspace.path(),
1586 &["hangprobe".to_string()],
1587 &ctx,
1588 Duration::from_secs(10),
1589 )
1590 .await
1591 .expect("a timed-out run still returns its output");
1592 assert!(run.stopped);
1593 assert!(
1594 String::from_utf8_lossy(&run.output.stdout).contains("test slow_case ... started"),
1595 "{:?}",
1596 run.output
1597 );
1598 let hung =
1599 codewhale_runtime::process_tree::read_pid_file(&pid_file, Duration::from_secs(5));
1600 assert!(
1601 codewhale_runtime::process_tree::wait_for_pid_exit(hung, Duration::from_secs(5)),
1602 "the timed-out run's process is still running"
1603 );
1604 }
1605
1606 #[test]
1607 fn zero_test_detector_flags_empty_filters_across_runners_and_allows_real_runs() {
1608 let cargo_filtered = detect_zero_tests_matched(
1609 "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 26 filtered out; finished in 0.00s\n",
1610 "",
1611 true,
1612 );
1613 assert!(cargo_filtered.zero_tests_matched);
1614 assert_eq!(cargo_filtered.tests_executed, Some(0));
1615 assert_eq!(cargo_filtered.tests_filtered_out, Some(26));
1616
1617 let cargo_multi_target_pass = detect_zero_tests_matched(
1618 "test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 21 filtered out; finished in 0.02s\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n",
1619 "",
1620 true,
1621 );
1622 assert!(!cargo_multi_target_pass.zero_tests_matched);
1623 assert_eq!(cargo_multi_target_pass.tests_executed, Some(5));
1624
1625 let cargo_unfiltered_empty = detect_zero_tests_matched(
1626 "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n",
1627 "",
1628 false,
1629 );
1630 assert!(!cargo_unfiltered_empty.zero_tests_matched);
1631
1632 let nextest_zero = detect_zero_tests_matched(
1633 "",
1634 "\x1b[1mSummary\x1b[0m [ 0.001s] 0 tests run: 0 passed, 12 skipped\n",
1635 true,
1636 );
1637 assert!(nextest_zero.zero_tests_matched);
1638 assert_eq!(nextest_zero.tests_executed, Some(0));
1639 assert_eq!(nextest_zero.tests_filtered_out, Some(12));
1640
1641 let pytest_zero = detect_zero_tests_matched(
1642 "collected 26 items / 26 deselected / 0 selected\n=== 26 deselected in 0.01s ===\n",
1643 "",
1644 true,
1645 );
1646 assert!(pytest_zero.zero_tests_matched);
1647 assert_eq!(pytest_zero.tests_filtered_out, Some(26));
1648
1649 let pytest_collected_zero =
1650 detect_zero_tests_matched("collected 0 items\n\nno tests ran in 0.00s\n", "", false);
1651 assert!(pytest_collected_zero.zero_tests_matched);
1652
1653 let vitest_zero =
1654 detect_zero_tests_matched("No test files found, exiting with code 0\n", "", true);
1655 assert!(vitest_zero.zero_tests_matched);
1656
1657 let jest_zero =
1658 detect_zero_tests_matched("No tests found, exiting with code 0\n", "", true);
1659 assert!(jest_zero.zero_tests_matched);
1660
1661 let go_zero = detect_zero_tests_matched(
1662 "testing: warning: no tests to run\nPASS\nok \texample.com/pkg\t0.002s\n",
1663 "",
1664 true,
1665 );
1666 assert!(go_zero.zero_tests_matched);
1667
1668 let go_pass = detect_zero_tests_matched(
1669 "--- PASS: TestOk (0.00s)\nPASS\nok \texample.com/pkg\t0.002s\n",
1670 "",
1671 true,
1672 );
1673 assert!(!go_pass.zero_tests_matched);
1674 }
1675
1676 #[tokio::test]
1677 async fn background_cargo_preserves_child_ownership_and_settlement() {
1678 if !cargo_available() {
1679 return;
1680 }
1681 let tmp = tempdir().expect("tempdir");
1682 let project_dir = init_cargo_project(tmp.path());
1683 fs::write(
1684 project_dir.join("src/lib.rs"),
1685 "#[test] fn waits() { std::thread::sleep(std::time::Duration::from_secs(2)); }",
1686 )
1687 .expect("write test");
1688 let ctx = ToolContext::new(&project_dir)
1689 .with_owner_agent("test-child", "verifier")
1690 .with_origin_tool_call_id("test-call")
1691 .with_origin_turn_id("test-turn");
1692 let result = RunTestsTool
1693 .execute(json!({"background": true}), &ctx)
1694 .await
1695 .expect("launch cargo");
1696 let output: RunTestsOutput = serde_json::from_str(&result.content).expect("json");
1697 let task_id = output.task_id.expect("task id");
1698 {
1699 let mut manager = ctx.shell_manager.lock().expect("shell manager");
1700 let job = manager
1701 .list_jobs_for_session(&ctx.state_namespace)
1702 .into_iter()
1703 .find(|job| job.id == task_id)
1704 .expect("child job");
1705 assert_eq!(job.owner_agent_id.as_deref(), Some("test-child"));
1706 assert_eq!(job.owner_agent_name.as_deref(), Some("verifier"));
1707 assert_eq!(job.origin_tool_call_id.as_deref(), Some("test-call"));
1708 assert_eq!(job.origin_turn_id.as_deref(), Some("test-turn"));
1709 assert_eq!(
1710 manager.running_owner_agent_ids_for_session(&ctx.state_namespace),
1711 vec!["test-child".to_string()]
1712 );
1713 }
1714 let settled = super::super::shell::BashTool::alias("task_shell_wait", "wait")
1715 .execute(json!({"task_id": task_id, "timeout_ms": 30_000}), &ctx)
1716 .await
1717 .expect("wait for child cargo");
1718 assert!(settled.success, "{}", settled.content);
1719 let mut manager = ctx.shell_manager.lock().expect("shell manager");
1720 assert!(
1721 manager
1722 .running_owner_agent_ids_for_session(&ctx.state_namespace)
1723 .is_empty()
1724 );
1725 assert!(
1726 manager
1727 .drain_finished_jobs_with_evidence_for_session(&ctx.state_namespace)
1728 .is_empty()
1729 );
1730 }
1731
1732 #[tokio::test]
1733 async fn run_tests_backgrounds_and_flags_zero_test_filters() {
1734 if !cargo_available() {
1735 return;
1736 }
1737 let tmp = tempdir().expect("tempdir");
1738 let project_dir = init_cargo_project(tmp.path());
1739 let ctx = ToolContext::new(&project_dir);
1740
1741 let zero_result = RunTestsTool
1742 .execute(json!({"args": "--lib definitely_no_such_test_name"}), &ctx)
1743 .await
1744 .expect("zero-test execute");
1745 let parsed_zero: RunTestsOutput = serde_json::from_str(&zero_result.content).expect("json");
1746 assert!(
1747 parsed_zero.zero_tests_matched,
1748 "expected zero_tests_matched: {}",
1749 zero_result.content
1750 );
1751 assert!(!parsed_zero.success, "{}", zero_result.content);
1752 assert_eq!(parsed_zero.tests_executed, Some(0));
1753 assert!(parsed_zero.tests_filtered_out.is_some_and(|n| n >= 1));
1754 assert!(parsed_zero.warning.is_some());
1755
1756 let bg_result = RunTestsTool
1757 .execute(json!({"background": true}), &ctx)
1758 .await
1759 .expect("background execute");
1760 let parsed_bg: RunTestsOutput = serde_json::from_str(&bg_result.content).expect("json");
1761 assert!(parsed_bg.success, "{}", bg_result.content);
1762 assert!(parsed_bg.backgrounded);
1763 assert_eq!(parsed_bg.status.as_deref(), Some("running"));
1764 let bg_task_id = parsed_bg.task_id.as_deref().expect("task_id");
1765 let bg_meta = bg_result.metadata.as_ref().expect("metadata");
1766 assert_eq!(bg_meta["backgrounded"], json!(true));
1767 assert_eq!(bg_meta["detached_start"], json!(true));
1768 assert_eq!(bg_meta["task_id"], json!(bg_task_id));
1769 let _ = ctx.shell_manager.lock().expect("lock").kill(bg_task_id);
1770
1771 let slow_lib = r#"
1772 #[cfg(test)]
1773 mod tests {
1774 #[test]
1775 fn slow_test() {
1776 std::thread::sleep(std::time::Duration::from_secs(5));
1777 }
1778 }
1779 "#;
1780 fs::write(project_dir.join("src/lib.rs"), slow_lib).expect("write slow test");
1781 let started = Instant::now();
1782 let auto_bg = RunTestsTool
1783 .execute(json!({"timeout_ms": 150}), &ctx)
1784 .await
1785 .expect("auto-background execute");
1786 assert!(
1787 started.elapsed() < Duration::from_secs(4),
1788 "auto-background took {:?}",
1789 started.elapsed()
1790 );
1791 let parsed_auto: RunTestsOutput = serde_json::from_str(&auto_bg.content).expect("json");
1792 assert!(parsed_auto.success, "{}", auto_bg.content);
1793 assert!(parsed_auto.backgrounded, "{}", auto_bg.content);
1794 assert_eq!(parsed_auto.status.as_deref(), Some("running"));
1795 let auto_task_id = parsed_auto.task_id.as_deref().expect("auto task_id");
1796 let _ = ctx.shell_manager.lock().expect("lock").kill(auto_task_id);
1797 }
1798 }
1799
1799 lines RUST