| 1 | use super::*; |
| 2 | |
| 3 | use crate::tools::spec::ToolContext; |
| 4 | use serde_json::{Value, json}; |
| 5 | #[cfg(unix)] |
| 6 | use std::sync::OnceLock; |
| 7 | use tempfile::tempdir; |
| 8 | |
| 9 | #[cfg(windows)] |
| 10 | use windows::Win32::Foundation::{DUPLICATE_HANDLE_OPTIONS, DuplicateHandle, HANDLE}; |
| 11 | #[cfg(windows)] |
| 12 | use windows::Win32::System::Threading::GetCurrentProcess; |
| 13 | |
| 14 | const BACKGROUND_COMPLETION_WAIT_MS: u64 = 30_000; |
| 15 | |
| 16 | #[test] |
| 17 | fn foreground_input_preserves_write_errors_and_stops_after_a_partial_write() { |
| 18 | let mut storage = [0; 2]; |
| 19 | let checks = std::cell::Cell::new(0); |
| 20 | let completed = write_foreground_input(&mut storage.as_mut_slice(), b"abcd", || { |
| 21 | let count = checks.get(); |
| 22 | checks.set(count + 1); |
| 23 | if count == 0 { |
| 24 | Duration::from_secs(1) |
| 25 | } else { |
| 26 | Duration::ZERO |
| 27 | } |
| 28 | }) |
| 29 | .unwrap(); |
| 30 | assert!(!completed); |
| 31 | assert_eq!(storage, *b"ab"); |
| 32 | assert_eq!(checks.get(), 2); |
| 33 | |
| 34 | let file = tempfile::NamedTempFile::new().unwrap(); |
| 35 | let mut read_only = std::fs::File::open(file.path()).unwrap(); |
| 36 | let expected = read_only.write(b"x").unwrap_err(); |
| 37 | let actual = |
| 38 | write_foreground_input(&mut read_only, b"x", || Duration::from_secs(1)).unwrap_err(); |
| 39 | assert_eq!(actual.raw_os_error(), expected.raw_os_error()); |
| 40 | } |
| 41 | |
| 42 | #[test] |
| 43 | fn foreground_input_round_trips_through_eof() { |
| 44 | let workspace = tempdir().unwrap(); |
| 45 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 46 | let sort = if cfg!(windows) { |
| 47 | "sort.exe" |
| 48 | } else { |
| 49 | "exec sort" |
| 50 | }; |
| 51 | let result = manager |
| 52 | .execute_with_options_env( |
| 53 | sort, |
| 54 | None, |
| 55 | 15_000, |
| 56 | false, |
| 57 | Some("pear\napple\n"), |
| 58 | false, |
| 59 | None, |
| 60 | HashMap::new(), |
| 61 | ) |
| 62 | .unwrap(); |
| 63 | assert_eq!(result.status, ShellStatus::Completed, "{result:?}"); |
| 64 | assert_eq!(result.exit_code, Some(0)); |
| 65 | assert_eq!(result.stdout.lines().collect::<Vec<_>>(), ["apple", "pear"]); |
| 66 | assert_eq!(result.stdout_len, result.stdout.len()); |
| 67 | assert_eq!(result.stdout_omitted, 0); |
| 68 | assert!(result.stderr.is_empty()); |
| 69 | } |
| 70 | |
| 71 | #[test] |
| 72 | fn foreground_input_delivers_multiple_pipe_buffers_in_order() { |
| 73 | const HELPER_ENV: &str = "CODEWHALE_TEST_FOREGROUND_STDIN_COPY"; |
| 74 | let input = (0..32_768) |
| 75 | .map(|n| format!("record-{n:05}\n")) |
| 76 | .collect::<String>(); |
| 77 | if std::env::var(HELPER_ENV).as_deref() == Ok("1") { |
| 78 | let mut received = Vec::new(); |
| 79 | std::io::stdin().lock().read_to_end(&mut received).unwrap(); |
| 80 | assert_eq!(received.len(), input.len()); |
| 81 | assert!( |
| 82 | received == input.as_bytes(), |
| 83 | "foreground input changed in transit" |
| 84 | ); |
| 85 | writeln!( |
| 86 | std::io::stdout().lock(), |
| 87 | "received {} bytes", |
| 88 | received.len() |
| 89 | ) |
| 90 | .unwrap(); |
| 91 | return; |
| 92 | } |
| 93 | let workspace = tempdir().unwrap(); |
| 94 | let manager = ShellManager::new(workspace.path().to_path_buf()); |
| 95 | let executable = std::env::current_exe().unwrap(); |
| 96 | let spec = CommandSpec::program( |
| 97 | executable.to_str().unwrap(), |
| 98 | vec![ |
| 99 | "--exact".into(), |
| 100 | "tools::shell::tests::foreground_input_delivers_multiple_pipe_buffers_in_order".into(), |
| 101 | "--nocapture".into(), |
| 102 | ], |
| 103 | workspace.path().to_owned(), |
| 104 | Duration::from_secs(30), |
| 105 | ) |
| 106 | .with_policy(manager.sandbox_policy.clone()) |
| 107 | .with_env(HashMap::from([(HELPER_ENV.into(), "1".into())])); |
| 108 | let env = manager.sandbox_manager.try_prepare(&spec).unwrap(); |
| 109 | let result = ShellManager::execute_sync_sandboxed( |
| 110 | "copy stdin", |
| 111 | workspace.path(), |
| 112 | 30_000, |
| 113 | Some(&input), |
| 114 | &env, |
| 115 | ) |
| 116 | .unwrap(); |
| 117 | assert_eq!(result.status, ShellStatus::Completed, "{result:?}"); |
| 118 | assert!( |
| 119 | result |
| 120 | .stdout |
| 121 | .contains(&format!("received {} bytes", input.len())), |
| 122 | "{result:?}" |
| 123 | ); |
| 124 | } |
| 125 | |
| 126 | #[test] |
| 127 | fn managed_program_preserves_resolved_path_and_argument_boundaries() { |
| 128 | const FIXTURE_ENV: &str = "CODEWHALE_TEST_ARGV_FIXTURE"; |
| 129 | if std::env::var(FIXTURE_ENV).as_deref() == Ok("1") { |
| 130 | let mut output = std::io::stdout().lock(); |
| 131 | writeln!( |
| 132 | output, |
| 133 | "\nargv fixture: {:?}", |
| 134 | std::env::args().collect::<Vec<_>>() |
| 135 | ) |
| 136 | .unwrap(); |
| 137 | return; |
| 138 | } |
| 139 | let workspace = tempdir().expect("tempdir"); |
| 140 | let program = std::env::current_exe().expect("test executable"); |
| 141 | let program = program.to_str().expect("UTF-8 test executable"); |
| 142 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 143 | for fixture in [ |
| 144 | r"C:\work\R&D\Cargo.toml", |
| 145 | r"C:\work\sample project\Cargo.toml", |
| 146 | r"C:\work\O'Brien\Cargo.toml", |
| 147 | r"C:\work\文档\Cargo.toml", |
| 148 | r"C:\work\sample project\", |
| 149 | "sample \"quoted\" name", |
| 150 | "", |
| 151 | ] { |
| 152 | let args = vec![ |
| 153 | "--nocapture".to_string(), |
| 154 | "--exact".to_string(), |
| 155 | "tools::shell::tests::managed_program_preserves_resolved_path_and_argument_boundaries" |
| 156 | .to_string(), |
| 157 | "--skip".to_string(), |
| 158 | fixture.to_string(), |
| 159 | ]; |
| 160 | let expected = Command::new(program) |
| 161 | .env(FIXTURE_ENV, "1") |
| 162 | .args(&args) |
| 163 | .current_dir(workspace.path()) |
| 164 | .output() |
| 165 | .expect("direct fixture"); |
| 166 | assert!(expected.status.success(), "{fixture:?}: {expected:?}"); |
| 167 | let started = manager |
| 168 | .execute_with_options_env_for_owner_and_work( |
| 169 | "argv fixture (display only)", |
| 170 | Some((program, &args)), |
| 171 | None, |
| 172 | 30_000, |
| 173 | true, |
| 174 | None, |
| 175 | false, |
| 176 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 177 | HashMap::from([(FIXTURE_ENV.to_string(), "1".to_string())]), |
| 178 | None, |
| 179 | "argv-fixture-session".to_string(), |
| 180 | None, |
| 181 | None, |
| 182 | None, |
| 183 | None, |
| 184 | false, |
| 185 | (1_000, 600_000), |
| 186 | ) |
| 187 | .expect("managed fixture"); |
| 188 | let task_id = started.task_id.expect("background job"); |
| 189 | let _ = manager.write_stdin(&task_id, "", true); |
| 190 | let actual = manager |
| 191 | .get_output(&task_id, true, BACKGROUND_COMPLETION_WAIT_MS) |
| 192 | .expect("fixture completion"); |
| 193 | assert_eq!( |
| 194 | actual.status, |
| 195 | ShellStatus::Completed, |
| 196 | "{fixture:?}: {actual:?}" |
| 197 | ); |
| 198 | assert_eq!(actual.exit_code, Some(0), "{fixture:?}: {actual:?}"); |
| 199 | let first = manager |
| 200 | .read_output_chunk(&task_id, ShellOutputStream::Stdout, 0, 7, 0) |
| 201 | .unwrap(); |
| 202 | let remaining = manager |
| 203 | .read_output_chunk( |
| 204 | &task_id, |
| 205 | ShellOutputStream::Stdout, |
| 206 | first.next_offset, |
| 207 | 65_536, |
| 208 | 0, |
| 209 | ) |
| 210 | .unwrap(); |
| 211 | assert_eq!( |
| 212 | [first.bytes, remaining.bytes].concat(), |
| 213 | actual.stdout.as_bytes() |
| 214 | ); |
| 215 | let expected_stdout = String::from_utf8(expected.stdout).expect("fixture output"); |
| 216 | let expected_argv = expected_stdout |
| 217 | .lines() |
| 218 | .find(|line| line.starts_with("argv fixture:")); |
| 219 | let actual_argv = actual |
| 220 | .stdout |
| 221 | .lines() |
| 222 | .find(|line| line.starts_with("argv fixture:")); |
| 223 | assert_eq!(actual_argv, expected_argv, "{fixture:?}: {}", actual.stdout); |
| 224 | assert_eq!(actual.stderr.as_bytes(), expected.stderr, "{fixture:?}"); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[test] |
| 229 | fn shell_catalog_guidance_matches_execution() { |
| 230 | let tool = LowercaseBashTool; |
| 231 | let schema = tool.input_schema(); |
| 232 | let command = schema["properties"]["command"]["description"] |
| 233 | .as_str() |
| 234 | .unwrap(); |
| 235 | let dispatcher = codewhale_sandbox::shell_dispatcher::global_dispatcher(); |
| 236 | assert!(command.contains(dispatcher.kind().binary())); |
| 237 | assert!( |
| 238 | !tool.description().contains(command), |
| 239 | "the command's interpreter guidance must appear once in each request" |
| 240 | ); |
| 241 | assert_eq!(tool.name(), "bash"); |
| 242 | assert!(tool.model_visible()); |
| 243 | assert!(!command.contains("action=run")); |
| 244 | assert!(tool.description().contains("background=true")); |
| 245 | assert!(tool.description().contains("cwd")); |
| 246 | assert!(tool.description().contains("description")); |
| 247 | assert!( |
| 248 | tool.description().contains( |
| 249 | "In Ask, after a sandbox denial, retry the exact command once with sandbox_permissions (the narrowest wider mode that suffices) and a one-sentence justification; the approval prompt asks the user." |
| 250 | ), |
| 251 | "foreground guidance must preserve the sandbox retry and approval contract" |
| 252 | ); |
| 253 | let legacy = BashTool::new("Bash"); |
| 254 | assert!(!legacy.model_visible()); |
| 255 | assert!(legacy.description().contains(command)); |
| 256 | assert!(legacy.description().contains("background=true")); |
| 257 | assert!(legacy.description().contains("wait=false")); |
| 258 | let readonly = BashTool::read_only("Bash"); |
| 259 | assert!(readonly.description().contains("never through a shell")); |
| 260 | assert!( |
| 261 | !readonly |
| 262 | .input_schema() |
| 263 | .to_string() |
| 264 | .contains("Actual execution shell") |
| 265 | ); |
| 266 | let alias = BashTool::alias("exec_shell", "run"); |
| 267 | assert_eq!(alias.description(), legacy.description()); |
| 268 | let workspace = tempdir().unwrap(); |
| 269 | let mut registry = crate::tools::ToolRegistry::new(ToolContext::new(workspace.path())); |
| 270 | registry.register(std::sync::Arc::new(BashTool::new("Bash"))); |
| 271 | registry.register(std::sync::Arc::new(LowercaseBashTool)); |
| 272 | let catalog = registry.to_api_tools(); |
| 273 | assert_eq!(catalog.len(), 1); |
| 274 | assert_eq!(catalog[0].name, "bash"); |
| 275 | assert_eq!(catalog[0].description, tool.description()); |
| 276 | assert_eq!( |
| 277 | catalog[0].input_schema["properties"]["command"]["description"], |
| 278 | command |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | #[test] |
| 283 | #[ignore = "Exports model-visible shell fixtures for opt-in live model evaluation"] |
| 284 | fn export_shell_guidance_eval_fixture() { |
| 285 | let path = std::env::var_os("SHELL_GUIDANCE_FIXTURE").expect("SHELL_GUIDANCE_FIXTURE"); |
| 286 | let workspace = tempdir().unwrap(); |
| 287 | let mut registry = crate::tools::ToolRegistry::new(ToolContext::new(workspace.path())); |
| 288 | registry.register(std::sync::Arc::new(BashTool::new("Bash"))); |
| 289 | registry.register(std::sync::Arc::new(LowercaseBashTool)); |
| 290 | let catalog = registry.to_api_tools(); |
| 291 | let tool = catalog.iter().find(|tool| tool.name == "bash").unwrap(); |
| 292 | let fixture = json!({ |
| 293 | "name": tool.name, |
| 294 | "description": tool.description, |
| 295 | "input_schema": tool.input_schema, |
| 296 | "shell": codewhale_sandbox::shell_dispatcher::global_dispatcher().kind().binary(), |
| 297 | }); |
| 298 | std::fs::write(path, serde_json::to_vec_pretty(&fixture).unwrap()).unwrap(); |
| 299 | } |
| 300 | |
| 301 | #[test] |
| 302 | fn lowercase_bash_schema_is_small_contract() { |
| 303 | let schema = LowercaseBashTool.input_schema(); |
| 304 | assert_eq!(schema["required"], json!(["command"])); |
| 305 | assert_eq!(schema["additionalProperties"], false); |
| 306 | assert_eq!( |
| 307 | schema["properties"] |
| 308 | .as_object() |
| 309 | .expect("properties") |
| 310 | .keys() |
| 311 | .cloned() |
| 312 | .collect::<std::collections::BTreeSet<_>>(), |
| 313 | [ |
| 314 | "background", |
| 315 | "command", |
| 316 | "cwd", |
| 317 | "description", |
| 318 | "justification", |
| 319 | "read_only", |
| 320 | "sandbox_permissions", |
| 321 | "timeout" |
| 322 | ] |
| 323 | .into_iter() |
| 324 | .map(str::to_string) |
| 325 | .collect() |
| 326 | ); |
| 327 | assert_eq!(schema["properties"]["cwd"]["type"], "string"); |
| 328 | assert_eq!(schema["properties"]["background"]["type"], "boolean"); |
| 329 | assert!(!BashTool::new("Bash").model_visible()); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn lowercase_bash_description_matches_the_timeout_it_actually_applies() { |
| 334 | use super::{ |
| 335 | CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS, contract_bash_legacy_input, |
| 336 | contract_bash_timeout_ms, |
| 337 | }; |
| 338 | |
| 339 | // `bash {command}` with no `timeout` translates to a legacy input carrying |
| 340 | // no `timeout_ms`. The contract delegate waits the 30 s default in the |
| 341 | // foreground, then moves a still-running process to the background. |
| 342 | let translated = |
| 343 | contract_bash_legacy_input(&json!({"command": "sleep 600"})).expect("translated input"); |
| 344 | assert!( |
| 345 | translated.get("timeout_ms").is_none(), |
| 346 | "omitting `timeout` must not synthesise one during translation: {translated}" |
| 347 | ); |
| 348 | assert_eq!( |
| 349 | contract_bash_timeout_ms(true, None, false, false), |
| 350 | Some(CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS) |
| 351 | ); |
| 352 | |
| 353 | // The tool description is the only place the model learns this. It used to |
| 354 | // say "when omitted there is no default timeout", so a model running a |
| 355 | // four-minute build had every reason not to pass a timeout, and got the |
| 356 | // process killed at two minutes anyway. It now names that wait and says |
| 357 | // the process is not killed there. |
| 358 | let description = LowercaseBashTool.description(); |
| 359 | assert!( |
| 360 | !description.contains("no default timeout"), |
| 361 | "description contradicts the applied default: {description}" |
| 362 | ); |
| 363 | let default_seconds = CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS / 1_000; |
| 364 | assert!( |
| 365 | description.contains(&format!("{default_seconds} seconds")), |
| 366 | "description must name the default it applies: {description}" |
| 367 | ); |
| 368 | let schema = LowercaseBashTool.input_schema(); |
| 369 | let timeout_doc = schema["properties"]["timeout"]["description"] |
| 370 | .as_str() |
| 371 | .expect("timeout description"); |
| 372 | assert!( |
| 373 | !timeout_doc.contains("no default timeout"), |
| 374 | "schema contradicts the applied default: {timeout_doc}" |
| 375 | ); |
| 376 | assert!( |
| 377 | timeout_doc.contains(&format!("{default_seconds} seconds")), |
| 378 | "schema must name the default it applies: {timeout_doc}" |
| 379 | ); |
| 380 | } |
| 381 | |
| 382 | #[test] |
| 383 | fn contract_bash_foreground_without_a_timeout_is_bounded_not_endless() { |
| 384 | use super::{ |
| 385 | BASH_MAX_TIMEOUT_MS, CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS, contract_bash_timeout_ms, |
| 386 | }; |
| 387 | |
| 388 | // The reported hang: `bash` in the foreground with no timeout. It used to |
| 389 | // resolve to BASH_MAX_TIMEOUT_MS (~24.8 days), so an unauthenticated CLI |
| 390 | // waiting on a prompt held the turn open indefinitely. It now takes the |
| 391 | // default the tool's own schema advertises, which is what arms the |
| 392 | // kill-and-rerun-in-background recovery. |
| 393 | assert_eq!( |
| 394 | contract_bash_timeout_ms(true, None, false, false), |
| 395 | Some(CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS) |
| 396 | ); |
| 397 | const { assert!(CONTRACT_BASH_FOREGROUND_DEFAULT_TIMEOUT_MS < BASH_MAX_TIMEOUT_MS) }; |
| 398 | |
| 399 | // An explicit request still wins, including one far above the default: |
| 400 | // long foreground work stays possible when the model asks for it. |
| 401 | assert_eq!( |
| 402 | contract_bash_timeout_ms(true, Some(1_800_000), false, false), |
| 403 | Some(1_800_000) |
| 404 | ); |
| 405 | assert_eq!( |
| 406 | contract_bash_timeout_ms(true, Some(5), false, false), |
| 407 | Some(5) |
| 408 | ); |
| 409 | |
| 410 | // Background and interactive runs are meant to outlive the call, so they |
| 411 | // keep "no timeout" and are never bounded by the foreground default. |
| 412 | assert_eq!(contract_bash_timeout_ms(true, None, true, false), None); |
| 413 | assert_eq!(contract_bash_timeout_ms(true, None, false, true), None); |
| 414 | |
| 415 | // The standalone Bash tools already resolve their own default upstream; |
| 416 | // this helper must not second-guess the value they pass in. |
| 417 | assert_eq!( |
| 418 | contract_bash_timeout_ms(false, Some(120_000), false, false), |
| 419 | Some(120_000) |
| 420 | ); |
| 421 | } |
| 422 | |
| 423 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 424 | #[test] |
| 425 | fn inherited_interactive_terminal_fails_closed_before_spawn() { |
| 426 | let workspace = tempdir().expect("workspace"); |
| 427 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 428 | let err = manager |
| 429 | .execute_interactive_with_policy_env("codew", None, 10_000, None, HashMap::new()) |
| 430 | .expect_err("Unix inherited-terminal takeover must not spawn"); |
| 431 | let message = err.to_string(); |
| 432 | assert!(message.contains("foreground TTY ownership"), "{message}"); |
| 433 | assert!(message.contains("terminal_run"), "{message}"); |
| 434 | assert!(message.contains("terminal_send"), "{message}"); |
| 435 | assert!(message.contains("omit `interactive: true`"), "{message}"); |
| 436 | } |
| 437 | |
| 438 | #[cfg(all(unix, target_env = "ohos"))] |
| 439 | #[test] |
| 440 | fn inherited_interactive_terminal_offers_only_ohos_recovery_paths() { |
| 441 | let workspace = tempdir().expect("workspace"); |
| 442 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 443 | let err = manager |
| 444 | .execute_interactive_with_policy_env("codew", None, 10_000, None, HashMap::new()) |
| 445 | .expect_err("OHOS inherited-terminal takeover must not spawn"); |
| 446 | let message = err.to_string(); |
| 447 | assert!(message.contains("foreground TTY ownership"), "{message}"); |
| 448 | assert!(message.contains("new terminal"), "{message}"); |
| 449 | assert!(message.contains("omit `interactive: true`"), "{message}"); |
| 450 | assert!(!message.contains("background: true"), "{message}"); |
| 451 | assert!(!message.contains("terminal_run"), "{message}"); |
| 452 | } |
| 453 | |
| 454 | #[test] |
| 455 | fn contract_bash_nonzero_is_an_error_with_status_after_output() { |
| 456 | let error = finish_contract_bash_result( |
| 457 | ShellResult { |
| 458 | task_id: None, |
| 459 | status: ShellStatus::Failed, |
| 460 | exit_code: Some(7), |
| 461 | stdout: "before".to_string(), |
| 462 | stderr: String::new(), |
| 463 | duration_ms: 1, |
| 464 | stdout_len: 6, |
| 465 | stderr_len: 0, |
| 466 | stdout_omitted: 0, |
| 467 | stderr_omitted: 0, |
| 468 | stdout_truncated: false, |
| 469 | stderr_truncated: false, |
| 470 | sandboxed: false, |
| 471 | sandbox_type: None, |
| 472 | sandbox_denied: false, |
| 473 | }, |
| 474 | None, |
| 475 | &ToolContext::new("."), |
| 476 | None, |
| 477 | false, |
| 478 | None, |
| 479 | None, |
| 480 | false, |
| 481 | None, |
| 482 | None, |
| 483 | ) |
| 484 | .expect_err("nonzero must be a failed tool call"); |
| 485 | assert!( |
| 486 | error |
| 487 | .to_string() |
| 488 | .ends_with("before\n\nCommand exited with code 7") |
| 489 | ); |
| 490 | // The error keeps the metadata a success carries, so hooks still see the |
| 491 | // exit code and status of a failing command. |
| 492 | let metadata = error.metadata().expect("failure metadata"); |
| 493 | assert_eq!(metadata["exit_code"], 7); |
| 494 | assert_eq!(metadata["status"], "Failed"); |
| 495 | } |
| 496 | |
| 497 | #[cfg(unix)] |
| 498 | #[tokio::test] |
| 499 | async fn lowercase_bash_returns_one_ordered_stream() { |
| 500 | let workspace = tempdir().expect("workspace"); |
| 501 | let context = ToolContext::new(workspace.path()); |
| 502 | let result = LowercaseBashTool |
| 503 | .execute( |
| 504 | json!({"command": "printf out-1; printf err-2 >&2; printf out-3"}), |
| 505 | &context, |
| 506 | ) |
| 507 | .await |
| 508 | .expect("bash"); |
| 509 | assert_eq!(result.content, "out-1err-2out-3"); |
| 510 | } |
| 511 | |
| 512 | /// #6689: the receipt is exact-or-absent, fits the hook bound after JSON |
| 513 | /// escaping, and reports how the run ended without inventing an exit code. |
| 514 | #[test] |
| 515 | fn execution_receipt_is_bounded_and_reports_truthful_state() { |
| 516 | let tmp = tempdir().unwrap(); |
| 517 | let identity = |command: &str, cwd: &Path| ShellExecutionIdentity { |
| 518 | command: command.to_string(), |
| 519 | cwd: cwd.to_path_buf(), |
| 520 | }; |
| 521 | let cwd = tmp.path().canonicalize().unwrap(); |
| 522 | let mut result = failed_network_shell_result( |
| 523 | &"\u{1f40b}\n\"\u{1}".repeat(12_000), |
| 524 | &"err\n".repeat(12_000), |
| 525 | ); |
| 526 | result.sandboxed = false; |
| 527 | result.sandbox_type = None; |
| 528 | result.stdout_truncated = true; |
| 529 | result.exit_code = None; |
| 530 | result.status = ShellStatus::Killed; |
| 531 | |
| 532 | let receipt = shell_execution_receipt(&identity("printf hi", &cwd), &result, "separate") |
| 533 | .expect("receipt"); |
| 534 | let encoded = serde_json::to_string(&receipt).unwrap(); |
| 535 | assert!(encoded.len() <= crate::hooks::HOOK_EXECUTION_RECEIPT_MAX_BYTES); |
| 536 | assert_eq!(serde_json::from_str::<Value>(&encoded).unwrap(), receipt); |
| 537 | assert_eq!(receipt["schema_version"], 1); |
| 538 | assert_eq!(receipt["command"], "printf hi"); |
| 539 | assert_eq!(receipt["cwd"], cwd.to_str().unwrap()); |
| 540 | assert_eq!(receipt["state"], "interrupted"); |
| 541 | assert!(receipt["exit_code"].is_null()); |
| 542 | assert_eq!(receipt["stdout_truncated"], true); |
| 543 | assert_eq!(receipt["stderr_truncated"], true); |
| 544 | assert!( |
| 545 | receipt["stderr"] |
| 546 | .as_str() |
| 547 | .unwrap() |
| 548 | .contains("[receipt preview truncated]") |
| 549 | ); |
| 550 | |
| 551 | // A nonzero exit is a completed run, and a 64-bit code survives. |
| 552 | result.status = ShellStatus::Failed; |
| 553 | result.exit_code = Some(3_221_225_477); |
| 554 | let receipt = shell_execution_receipt(&identity("x", &cwd), &result, "combined").unwrap(); |
| 555 | assert_eq!(receipt["state"], "completed"); |
| 556 | assert_eq!(receipt["exit_code"], 3_221_225_477_i64); |
| 557 | assert_eq!(receipt["output_kind"], "combined"); |
| 558 | |
| 559 | result.status = ShellStatus::TimedOut; |
| 560 | result.exit_code = None; |
| 561 | let receipt = shell_execution_receipt(&identity("x", &cwd), &result, "separate").unwrap(); |
| 562 | assert_eq!(receipt["state"], "interrupted"); |
| 563 | |
| 564 | // Absent, never truncated or guessed. |
| 565 | result.status = ShellStatus::Running; |
| 566 | assert!(shell_execution_receipt(&identity("x", &cwd), &result, "separate").is_none()); |
| 567 | result.status = ShellStatus::Completed; |
| 568 | for command in ["", "bad\0command"] { |
| 569 | assert!(shell_execution_receipt(&identity(command, &cwd), &result, "separate").is_none()); |
| 570 | } |
| 571 | let long = "x".repeat(EXECUTION_RECEIPT_IDENTITY_MAX_BYTES + 1); |
| 572 | assert!(shell_execution_receipt(&identity(&long, &cwd), &result, "separate").is_none()); |
| 573 | let long_cwd = PathBuf::from(format!("/{long}")); |
| 574 | assert!(shell_execution_receipt(&identity("x", &long_cwd), &result, "separate").is_none()); |
| 575 | assert!( |
| 576 | shell_execution_receipt(&identity("x", Path::new("relative")), &result, "separate") |
| 577 | .is_none() |
| 578 | ); |
| 579 | result.sandboxed = true; |
| 580 | assert!(shell_execution_receipt(&identity("x", &cwd), &result, "separate").is_none()); |
| 581 | } |
| 582 | |
| 583 | /// #6689: a settled foreground run records the command and directory the |
| 584 | /// process manager spawned, on success and on failure, and background runs |
| 585 | /// carry no receipt. The workspace is opened through a symlink so the default |
| 586 | /// directory and an explicit `cwd` would otherwise be spelled differently. |
| 587 | #[cfg(unix)] |
| 588 | #[tokio::test] |
| 589 | async fn foreground_shell_results_carry_the_spawned_execution_receipt() { |
| 590 | let tmp = tempdir().unwrap(); |
| 591 | let real = tmp.path().join("real"); |
| 592 | std::fs::create_dir_all(real.join("child")).unwrap(); |
| 593 | let workspace = tmp.path().join("link"); |
| 594 | std::os::unix::fs::symlink(&real, &workspace).unwrap(); |
| 595 | let mut context = ToolContext::new(workspace.clone()) |
| 596 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::DangerFullAccess); |
| 597 | context.auto_approve = true; |
| 598 | let tool = BashTool::new("Bash"); |
| 599 | |
| 600 | // No completion hook registered: nothing reads a receipt, so none rides |
| 601 | // along in the metadata the Runtime API persists. |
| 602 | let unobserved = tool |
| 603 | .execute(json!({"command": "pwd"}), &context) |
| 604 | .await |
| 605 | .unwrap(); |
| 606 | assert!( |
| 607 | unobserved |
| 608 | .metadata |
| 609 | .as_ref() |
| 610 | .unwrap() |
| 611 | .get("execution_receipt") |
| 612 | .is_none() |
| 613 | ); |
| 614 | |
| 615 | let hooks = crate::hooks::HookExecutor::new( |
| 616 | codewhale_config::hooks::HooksConfig { |
| 617 | enabled: true, |
| 618 | hooks: vec![codewhale_config::hooks::Hook::new( |
| 619 | codewhale_config::hooks::HookEvent::ToolCallAfter, |
| 620 | "true", |
| 621 | )], |
| 622 | ..codewhale_config::hooks::HooksConfig::default() |
| 623 | }, |
| 624 | workspace.clone(), |
| 625 | ); |
| 626 | context.runtime.hook_executor = Some(std::sync::Arc::new(hooks)); |
| 627 | // Exact strings, not re-canonicalized: both spellings must already agree. |
| 628 | let real = real.canonicalize().unwrap(); |
| 629 | let real_str = real.to_str().unwrap(); |
| 630 | let child_str = real.join("child"); |
| 631 | let child_str = child_str.to_str().unwrap(); |
| 632 | |
| 633 | let default_dir = tool |
| 634 | .execute(json!({"command": "pwd"}), &context) |
| 635 | .await |
| 636 | .unwrap(); |
| 637 | let explicit_dir = tool |
| 638 | .execute(json!({"command": "pwd", "cwd": "."}), &context) |
| 639 | .await |
| 640 | .unwrap(); |
| 641 | for result in [&default_dir, &explicit_dir] { |
| 642 | assert_eq!( |
| 643 | result.metadata.as_ref().unwrap()["execution_receipt"]["cwd"], |
| 644 | real_str |
| 645 | ); |
| 646 | } |
| 647 | |
| 648 | let command = "printf effective; printf diagnostic >&2; exit 7"; |
| 649 | let result = tool |
| 650 | .execute(json!({"command": command, "cwd": "child"}), &context) |
| 651 | .await |
| 652 | .unwrap(); |
| 653 | let receipt = &result.metadata.as_ref().unwrap()["execution_receipt"]; |
| 654 | assert_eq!(receipt["command"], command); |
| 655 | assert_eq!(receipt["cwd"], child_str); |
| 656 | assert_eq!(receipt["stdout"], "effective"); |
| 657 | assert_eq!(receipt["stderr"], "diagnostic"); |
| 658 | assert_eq!(receipt["exit_code"], 7); |
| 659 | assert_eq!(receipt["state"], "completed"); |
| 660 | assert_eq!(receipt["output_kind"], "separate"); |
| 661 | |
| 662 | let interrupted = tool |
| 663 | .execute(json!({"command": "kill -TERM $$"}), &context) |
| 664 | .await |
| 665 | .unwrap(); |
| 666 | let receipt = &interrupted.metadata.as_ref().unwrap()["execution_receipt"]; |
| 667 | assert_eq!(receipt["state"], "interrupted"); |
| 668 | assert!(receipt["exit_code"].is_null()); |
| 669 | |
| 670 | let background = tool |
| 671 | .execute( |
| 672 | json!({"command": "printf background", "background": true}), |
| 673 | &context, |
| 674 | ) |
| 675 | .await |
| 676 | .unwrap(); |
| 677 | assert!( |
| 678 | background |
| 679 | .metadata |
| 680 | .as_ref() |
| 681 | .unwrap() |
| 682 | .get("execution_receipt") |
| 683 | .is_none() |
| 684 | ); |
| 685 | |
| 686 | // Lowercase `bash` shares one pipe: the preview is combined output, and a |
| 687 | // failing command's error still carries the receipt for hooks. |
| 688 | let result = LowercaseBashTool |
| 689 | .execute( |
| 690 | json!({"command": "printf merged; printf diagnostic >&2"}), |
| 691 | &context, |
| 692 | ) |
| 693 | .await |
| 694 | .unwrap(); |
| 695 | let receipt = &result.metadata.as_ref().unwrap()["execution_receipt"]; |
| 696 | assert_eq!(receipt["output_kind"], "combined"); |
| 697 | assert_eq!(receipt["stdout"], "mergeddiagnostic"); |
| 698 | assert_eq!(receipt["stderr"], ""); |
| 699 | assert_eq!(receipt["state"], "completed"); |
| 700 | let error = LowercaseBashTool |
| 701 | .execute(json!({"command": "printf partial; exit 3"}), &context) |
| 702 | .await |
| 703 | .expect_err("nonzero exit is a failed bash call"); |
| 704 | let receipt = &error.metadata().expect("failure metadata")["execution_receipt"]; |
| 705 | assert_eq!(receipt["command"], "printf partial; exit 3"); |
| 706 | assert_eq!(receipt["exit_code"], 3); |
| 707 | assert_eq!(receipt["state"], "completed"); |
| 708 | assert_eq!(receipt["cwd"], real_str); |
| 709 | } |
| 710 | |
| 711 | /// A post-run lookup of a retargeted workspace symlink would falsely name |
| 712 | /// the replacement directory. The receipt must keep the actual spawn path. |
| 713 | #[cfg(unix)] |
| 714 | #[tokio::test] |
| 715 | async fn execution_receipt_keeps_spawn_cwd_when_the_command_retargets_the_workspace() { |
| 716 | let tmp = tempdir().unwrap(); |
| 717 | let real = tmp.path().join("real"); |
| 718 | let other = tmp.path().join("other"); |
| 719 | std::fs::create_dir(&real).unwrap(); |
| 720 | std::fs::create_dir(&other).unwrap(); |
| 721 | let workspace = tmp.path().join("link"); |
| 722 | std::os::unix::fs::symlink(&real, &workspace).unwrap(); |
| 723 | let mut context = ToolContext::new(workspace.clone()) |
| 724 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::DangerFullAccess); |
| 725 | context.auto_approve = true; |
| 726 | context.runtime.hook_executor = Some(std::sync::Arc::new(crate::hooks::HookExecutor::new( |
| 727 | codewhale_config::hooks::HooksConfig { |
| 728 | enabled: true, |
| 729 | hooks: vec![codewhale_config::hooks::Hook::new( |
| 730 | codewhale_config::hooks::HookEvent::ToolCallAfter, |
| 731 | "true", |
| 732 | )], |
| 733 | ..codewhale_config::hooks::HooksConfig::default() |
| 734 | }, |
| 735 | workspace.clone(), |
| 736 | ))); |
| 737 | let command = "pwd -P; rm ../link; ln -s other ../link; pwd -P"; |
| 738 | let result = BashTool::new("Bash") |
| 739 | .execute(json!({"command": command}), &context) |
| 740 | .await |
| 741 | .unwrap(); |
| 742 | assert!(result.success); |
| 743 | let receipt = &result.metadata.as_ref().unwrap()["execution_receipt"]; |
| 744 | let actual = real.canonicalize().unwrap(); |
| 745 | let actual = actual.to_str().unwrap(); |
| 746 | assert_eq!(receipt["command"], command); |
| 747 | assert_eq!(receipt["cwd"], actual); |
| 748 | assert_eq!(receipt["stdout"], format!("{actual}\n{actual}\n")); |
| 749 | assert_eq!(receipt["exit_code"], 0); |
| 750 | assert_eq!( |
| 751 | workspace.canonicalize().unwrap(), |
| 752 | other.canonicalize().unwrap() |
| 753 | ); |
| 754 | } |
| 755 | |
| 756 | #[cfg(unix)] |
| 757 | #[tokio::test] |
| 758 | async fn lowercase_bash_keeps_raw_command_under_readonly_policy() { |
| 759 | let workspace = tempdir().expect("workspace"); |
| 760 | let context = ToolContext::new(workspace.path()) |
| 761 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 762 | let result = LowercaseBashTool |
| 763 | .execute(json!({"command": "pwd"}), &context) |
| 764 | .await |
| 765 | .expect("read-only bash"); |
| 766 | assert_eq!( |
| 767 | result.content.trim(), |
| 768 | workspace |
| 769 | .path() |
| 770 | .canonicalize() |
| 771 | .expect("canonical workspace") |
| 772 | .display() |
| 773 | .to_string() |
| 774 | ); |
| 775 | } |
| 776 | |
| 777 | #[tokio::test] |
| 778 | async fn lowercase_bash_readonly_refusal_names_work_mode() { |
| 779 | let workspace = tempdir().expect("workspace"); |
| 780 | let context = ToolContext::new(workspace.path()) |
| 781 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 782 | let error = LowercaseBashTool |
| 783 | .execute(json!({"command": "touch blocked-by-plan"}), &context) |
| 784 | .await |
| 785 | .expect_err("policy refusal is a typed denial"); |
| 786 | |
| 787 | assert!( |
| 788 | matches!(error, ToolError::PermissionDenied { .. }), |
| 789 | "{error}" |
| 790 | ); |
| 791 | let message = error.to_string(); |
| 792 | assert!( |
| 793 | message.contains("The user can change modes with /mode."), |
| 794 | "{message}" |
| 795 | ); |
| 796 | assert!(!message.contains("Work mode")); |
| 797 | assert!(!message.contains("switch to"), "{message}"); |
| 798 | assert!(!workspace.path().join("blocked-by-plan").exists()); |
| 799 | } |
| 800 | |
| 801 | /// Regression for the wedge that took out the owner's own session under swap |
| 802 | /// exhaustion: the lowercase `bash` spill file could not be created (full temp |
| 803 | /// volume), every call — including `echo ok` — failed with the harness-internal |
| 804 | /// "Failed to create streaming shell output", and nothing recovered. Spill |
| 805 | /// failure must be soft: the command still runs, the tail is still returned, |
| 806 | /// the next call still works, and no job state leaks. |
| 807 | #[cfg(unix)] |
| 808 | #[tokio::test] |
| 809 | async fn lowercase_bash_survives_spill_file_failure_and_stays_usable() { |
| 810 | let workspace = tempdir().expect("workspace"); |
| 811 | let context = ToolContext::new(workspace.path()); |
| 812 | let missing_spill_dir = workspace.path().join("no-such-temp-volume"); |
| 813 | assert!(!missing_spill_dir.exists()); |
| 814 | context |
| 815 | .shell_manager |
| 816 | .lock() |
| 817 | .expect("shell manager") |
| 818 | .set_output_spill_dir_for_test(Some(missing_spill_dir.clone())); |
| 819 | |
| 820 | // (ii) the command runs and (i) no harness-internal error leaks. |
| 821 | let first = LowercaseBashTool |
| 822 | .execute(json!({"command": echo_command("ok")}), &context) |
| 823 | .await |
| 824 | .expect("bash runs even when the spill file cannot be created"); |
| 825 | assert!(first.success, "{}", first.content); |
| 826 | assert_eq!(first.content.trim(), "ok"); |
| 827 | assert!( |
| 828 | !first |
| 829 | .content |
| 830 | .contains("Failed to create streaming shell output") |
| 831 | ); |
| 832 | |
| 833 | // The next call must work too — the whole point of the fix. |
| 834 | let second = LowercaseBashTool |
| 835 | .execute(json!({"command": echo_command("still-ok")}), &context) |
| 836 | .await |
| 837 | .expect("second bash call after a spill failure"); |
| 838 | assert!(second.success, "{}", second.content); |
| 839 | assert_eq!(second.content.trim(), "still-ok"); |
| 840 | |
| 841 | // Output past the bound is still delivered, and the notice explains why the |
| 842 | // full-output path is missing instead of pointing at a file that was never |
| 843 | // written. |
| 844 | let long = LowercaseBashTool |
| 845 | .execute( |
| 846 | json!({"command": "i=0; while [ $i -lt 2100 ]; do echo line-$i; i=$((i+1)); done"}), |
| 847 | &context, |
| 848 | ) |
| 849 | .await |
| 850 | .expect("long bash output without a spill file"); |
| 851 | assert!(long.success, "{}", long.content); |
| 852 | assert!(long.content.contains("line-2099")); |
| 853 | assert!( |
| 854 | long.content.contains("Full output was not persisted:"), |
| 855 | "{}", |
| 856 | long.content |
| 857 | ); |
| 858 | assert!(!long.content.contains("Full output: ")); |
| 859 | |
| 860 | // (iii) no leaked session state: nothing is still running or unowned-pending. |
| 861 | let mut manager = context.shell_manager.lock().expect("shell manager"); |
| 862 | let running = manager |
| 863 | .list_jobs() |
| 864 | .into_iter() |
| 865 | .filter(|job| job.status == ShellStatus::Running) |
| 866 | .count(); |
| 867 | assert_eq!(running, 0, "no shell job may be left running"); |
| 868 | assert!( |
| 869 | !missing_spill_dir.exists(), |
| 870 | "fail-soft must not create the dir" |
| 871 | ); |
| 872 | } |
| 873 | |
| 874 | /// A spawn/stream failure caused by host exhaustion must reach the model as |
| 875 | /// an actionable message (cause chain + likely reason + retry), never as a |
| 876 | /// bare harness-internal context string. |
| 877 | #[test] |
| 878 | fn shell_execution_failure_names_resource_exhaustion_and_says_retry() { |
| 879 | let error = anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::StorageFull)) |
| 880 | .context("Failed to open PTY"); |
| 881 | let message = shell_execution_failed_message(&error); |
| 882 | assert!( |
| 883 | message.starts_with("Shell execution failed: Failed to open PTY"), |
| 884 | "{message}" |
| 885 | ); |
| 886 | assert!( |
| 887 | message.contains("Likely host resource exhaustion"), |
| 888 | "{message}" |
| 889 | ); |
| 890 | assert!(message.contains("disk"), "{message}"); |
| 891 | assert!(message.contains("retry"), "{message}"); |
| 892 | assert!(message.contains("still usable"), "{message}"); |
| 893 | |
| 894 | #[cfg(unix)] |
| 895 | { |
| 896 | let error = anyhow::Error::from(std::io::Error::from_raw_os_error(libc::EMFILE)) |
| 897 | .context("Failed to spawn PTY command: echo ok"); |
| 898 | let message = shell_execution_failed_message(&error); |
| 899 | assert!(message.contains("file descriptors"), "{message}"); |
| 900 | assert!(message.contains("echo ok"), "{message}"); |
| 901 | } |
| 902 | |
| 903 | let plain = anyhow::anyhow!("working directory does not exist"); |
| 904 | let message = shell_execution_failed_message(&plain); |
| 905 | assert_eq!( |
| 906 | message, |
| 907 | "Shell execution failed: working directory does not exist" |
| 908 | ); |
| 909 | } |
| 910 | |
| 911 | fn execute_shell( |
| 912 | manager: &mut ShellManager, |
| 913 | command: &str, |
| 914 | working_dir: Option<&str>, |
| 915 | timeout_ms: u64, |
| 916 | background: bool, |
| 917 | ) -> Result<ShellResult> { |
| 918 | manager.execute_with_options_env_for_session( |
| 919 | command, |
| 920 | working_dir, |
| 921 | timeout_ms, |
| 922 | background, |
| 923 | None, |
| 924 | false, |
| 925 | None, |
| 926 | HashMap::new(), |
| 927 | "workspace", |
| 928 | ) |
| 929 | } |
| 930 | |
| 931 | #[test] |
| 932 | fn deleted_saved_workspace_reports_path_and_recovery_before_spawn() { |
| 933 | let workspace = tempdir().expect("workspace"); |
| 934 | let stale = workspace.path().join("deleted-session-workspace"); |
| 935 | let mut manager = ShellManager::new(stale.clone()); |
| 936 | |
| 937 | let error = execute_shell(&mut manager, "echo should-not-run", None, 1_000, false) |
| 938 | .expect_err("missing saved workspace must fail before shell spawn"); |
| 939 | let message = error.to_string(); |
| 940 | assert!(message.contains("saved session workspace is unavailable")); |
| 941 | assert!(message.contains(&stale.display().to_string())); |
| 942 | assert!(message.contains("working_dir") || message.contains("cwd")); |
| 943 | assert!(message.contains("resume/fork")); |
| 944 | } |
| 945 | |
| 946 | #[test] |
| 947 | fn explicit_missing_working_dir_is_not_misreported_as_session_corruption() { |
| 948 | let workspace = tempdir().expect("workspace"); |
| 949 | let missing = workspace.path().join("explicit-missing"); |
| 950 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 951 | |
| 952 | let error = execute_shell( |
| 953 | &mut manager, |
| 954 | "echo should-not-run", |
| 955 | missing.to_str(), |
| 956 | 1_000, |
| 957 | false, |
| 958 | ) |
| 959 | .expect_err("missing explicit cwd must fail before shell spawn"); |
| 960 | let message = error.to_string(); |
| 961 | assert!(message.contains("requested working directory is unavailable")); |
| 962 | assert!(message.contains(&missing.display().to_string())); |
| 963 | assert!(!message.contains("saved session workspace")); |
| 964 | } |
| 965 | |
| 966 | #[cfg(not(target_env = "ohos"))] |
| 967 | #[test] |
| 968 | fn pty_exit_status_preserves_high_windows_code_losslessly() { |
| 969 | let raw = 0xC000_0005; |
| 970 | let status = ShellExitStatus::from_pty(portable_pty::ExitStatus::with_exit_code(raw)); |
| 971 | |
| 972 | assert!(!status.success); |
| 973 | assert_eq!(status.code, Some(i64::from(raw))); |
| 974 | assert_eq!( |
| 975 | exit_code_label(status.code), |
| 976 | "exit code 3221225477 (0xC0000005)" |
| 977 | ); |
| 978 | assert_eq!(exit_code_hex(status.code).as_deref(), Some("0xC0000005")); |
| 979 | } |
| 980 | |
| 981 | #[cfg(not(target_env = "ohos"))] |
| 982 | #[test] |
| 983 | fn ordinary_pty_exit_status_keeps_concise_label() { |
| 984 | let status = ShellExitStatus::from_pty(portable_pty::ExitStatus::with_exit_code(127)); |
| 985 | |
| 986 | assert_eq!(status.code, Some(127)); |
| 987 | assert_eq!(exit_code_label(status.code), "exit code 127"); |
| 988 | assert_eq!(exit_code_hex(status.code), None); |
| 989 | } |
| 990 | |
| 991 | #[cfg(windows)] |
| 992 | #[test] |
| 993 | fn std_windows_exit_status_reinterprets_signed_dword() { |
| 994 | assert_eq!(std_exit_code_i64(0xC000_0005_u32 as i32), 0xC000_0005); |
| 995 | } |
| 996 | |
| 997 | #[cfg(windows)] |
| 998 | const JOB_OBJECT_QUERY_ACCESS: u32 = 0x0004; |
| 999 | |
| 1000 | #[cfg(windows)] |
| 1001 | fn duplicate_job_without_terminate_access(job: WindowsJob) -> WindowsJob { |
| 1002 | let process = unsafe { GetCurrentProcess() }; |
| 1003 | let mut limited_handle = HANDLE::default(); |
| 1004 | |
| 1005 | unsafe { |
| 1006 | DuplicateHandle( |
| 1007 | process, |
| 1008 | job.handle, |
| 1009 | process, |
| 1010 | &mut limited_handle, |
| 1011 | JOB_OBJECT_QUERY_ACCESS, |
| 1012 | false, |
| 1013 | DUPLICATE_HANDLE_OPTIONS(0), |
| 1014 | ) |
| 1015 | .expect("duplicate job handle without terminate access"); |
| 1016 | } |
| 1017 | |
| 1018 | drop(job); |
| 1019 | WindowsJob { |
| 1020 | handle: limited_handle, |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | fn echo_command(message: &str) -> String { |
| 1025 | format!("echo {message}") |
| 1026 | } |
| 1027 | |
| 1028 | fn sleep_command(seconds: u64) -> String { |
| 1029 | let dispatcher = codewhale_sandbox::shell_dispatcher::global_dispatcher(); |
| 1030 | if dispatcher.kind().is_powershell() { |
| 1031 | return format!("Start-Sleep -Seconds {seconds}"); |
| 1032 | } |
| 1033 | #[cfg(windows)] |
| 1034 | { |
| 1035 | let ping_count = seconds.saturating_add(1); |
| 1036 | format!("ping 127.0.0.1 -n {ping_count} > NUL") |
| 1037 | } |
| 1038 | #[cfg(not(windows))] |
| 1039 | { |
| 1040 | format!("sleep {seconds}") |
| 1041 | } |
| 1042 | } |
| 1043 | |
| 1044 | fn sleep_then_echo_command(seconds: u64, message: &str) -> String { |
| 1045 | let dispatcher = codewhale_sandbox::shell_dispatcher::global_dispatcher(); |
| 1046 | if dispatcher.kind().is_powershell() { |
| 1047 | return format!("Start-Sleep -Seconds {seconds}; echo {message}"); |
| 1048 | } |
| 1049 | #[cfg(windows)] |
| 1050 | { |
| 1051 | let ping_count = seconds.saturating_add(1); |
| 1052 | format!("ping 127.0.0.1 -n {ping_count} > NUL && echo {message}") |
| 1053 | } |
| 1054 | #[cfg(not(windows))] |
| 1055 | { |
| 1056 | format!("sleep {seconds} && echo {message}") |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | fn echo_stdin_command() -> String { |
| 1061 | let dispatcher = codewhale_sandbox::shell_dispatcher::global_dispatcher(); |
| 1062 | if dispatcher.kind().is_powershell() { |
| 1063 | return "[Console]::In.ReadToEnd()".to_string(); |
| 1064 | } |
| 1065 | #[cfg(windows)] |
| 1066 | { |
| 1067 | "more".to_string() |
| 1068 | } |
| 1069 | #[cfg(not(windows))] |
| 1070 | { |
| 1071 | "cat".to_string() |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | fn network_restricted_context(tmp: &std::path::Path) -> ToolContext { |
| 1076 | ToolContext::new(tmp) |
| 1077 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::WorkspaceWrite { |
| 1078 | writable_roots: vec![tmp.to_path_buf()], |
| 1079 | network_access: false, |
| 1080 | exclude_tmpdir: false, |
| 1081 | exclude_slash_tmp: false, |
| 1082 | }) |
| 1083 | .with_shell_network_denied_hint( |
| 1084 | "Shell command blocked: Plan mode runs shell commands in a network-restricted sandbox.", |
| 1085 | ) |
| 1086 | } |
| 1087 | |
| 1088 | fn failed_network_shell_result(stdout: &str, stderr: &str) -> ShellResult { |
| 1089 | ShellResult { |
| 1090 | task_id: None, |
| 1091 | status: ShellStatus::Failed, |
| 1092 | exit_code: Some(6), |
| 1093 | stdout: stdout.to_string(), |
| 1094 | stderr: stderr.to_string(), |
| 1095 | duration_ms: 25, |
| 1096 | stdout_len: stdout.len(), |
| 1097 | stderr_len: stderr.len(), |
| 1098 | stdout_omitted: 0, |
| 1099 | stderr_omitted: 0, |
| 1100 | stdout_truncated: false, |
| 1101 | stderr_truncated: false, |
| 1102 | sandboxed: true, |
| 1103 | sandbox_type: Some("seatbelt".to_string()), |
| 1104 | sandbox_denied: false, |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | #[cfg(unix)] |
| 1109 | const SHELL_DESCENDANT_HELPER_ENV: &str = "CODEWHALE_SHELL_DESCENDANT_HELPER"; |
| 1110 | #[cfg(unix)] |
| 1111 | const SHELL_DESCENDANT_PID_FILE_ENV: &str = "CODEWHALE_SHELL_DESCENDANT_PID_FILE"; |
| 1112 | |
| 1113 | #[cfg(unix)] |
| 1114 | #[test] |
| 1115 | fn shell_descendant_helper_process() { |
| 1116 | if std::env::var(SHELL_DESCENDANT_HELPER_ENV).ok().as_deref() != Some("1") { |
| 1117 | return; |
| 1118 | } |
| 1119 | let pid_file = |
| 1120 | PathBuf::from(std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("descendant pid file")); |
| 1121 | let mut child = Command::new("sleep") |
| 1122 | .arg("30") |
| 1123 | .spawn() |
| 1124 | .expect("spawn cheap descendant"); |
| 1125 | std::fs::write(pid_file, child.id().to_string()).expect("write descendant pid"); |
| 1126 | std::thread::sleep(Duration::from_secs(30)); |
| 1127 | let _ = child.wait(); |
| 1128 | } |
| 1129 | |
| 1130 | #[cfg(unix)] |
| 1131 | fn wait_for_shell_pid_file(path: &Path) -> libc::pid_t { |
| 1132 | let deadline = Instant::now() + Duration::from_secs(5); |
| 1133 | loop { |
| 1134 | if let Ok(raw) = std::fs::read_to_string(path) |
| 1135 | && let Ok(pid) = raw.trim().parse() |
| 1136 | { |
| 1137 | return pid; |
| 1138 | } |
| 1139 | assert!( |
| 1140 | Instant::now() < deadline, |
| 1141 | "descendant pid file never appeared" |
| 1142 | ); |
| 1143 | std::thread::sleep(Duration::from_millis(25)); |
| 1144 | } |
| 1145 | } |
| 1146 | |
| 1147 | #[cfg(unix)] |
| 1148 | fn wait_for_shell_pid_exit(pid: libc::pid_t) -> bool { |
| 1149 | let deadline = Instant::now() + Duration::from_secs(2); |
| 1150 | loop { |
| 1151 | if unsafe { libc::kill(pid, 0) } != 0 |
| 1152 | && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) |
| 1153 | { |
| 1154 | return true; |
| 1155 | } |
| 1156 | if Instant::now() >= deadline { |
| 1157 | return false; |
| 1158 | } |
| 1159 | std::thread::sleep(Duration::from_millis(25)); |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | fn wait_for_completed_shell(manager: &mut ShellManager, task_id: &str) -> ShellResult { |
| 1164 | let deadline = Instant::now() + Duration::from_millis(BACKGROUND_COMPLETION_WAIT_MS); |
| 1165 | |
| 1166 | loop { |
| 1167 | let result = manager |
| 1168 | .get_output(task_id, true, 1_000) |
| 1169 | .expect("get_output"); |
| 1170 | if result.status != ShellStatus::Running || Instant::now() >= deadline { |
| 1171 | return result; |
| 1172 | } |
| 1173 | std::thread::sleep(Duration::from_millis(50)); |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | #[test] |
| 1178 | fn shell_owner_registers_before_spawn_and_silent_work_stays_live() { |
| 1179 | let work = crate::work_graph::new_shared_work_runtime( |
| 1180 | crate::tools::todo::new_shared_todo_list(), |
| 1181 | crate::tools::plan::new_shared_plan_state(), |
| 1182 | ); |
| 1183 | let lifecycle = ShellWorkLifecycle { |
| 1184 | work: work.clone(), |
| 1185 | session_id: "shell-session".to_string(), |
| 1186 | }; |
| 1187 | |
| 1188 | { |
| 1189 | let _guard = ShellSpawnIntentGuard::new( |
| 1190 | Some(lifecycle.clone()), |
| 1191 | "shell_spawn_failure", |
| 1192 | "missing-program", |
| 1193 | ); |
| 1194 | } |
| 1195 | lifecycle |
| 1196 | .register("shell_silent", "sleep 30") |
| 1197 | .expect("register silent shell"); |
| 1198 | lifecycle |
| 1199 | .observe("shell_silent", &ShellStatus::Running, 1, 0) |
| 1200 | .expect("live owner observation"); |
| 1201 | lifecycle |
| 1202 | .observe("shell_silent", &ShellStatus::Running, 2, 512) |
| 1203 | .expect("growing output observation"); |
| 1204 | |
| 1205 | let graph = work |
| 1206 | .capture(Some("shell-session")) |
| 1207 | .expect("capture") |
| 1208 | .expect("graph") |
| 1209 | .graph; |
| 1210 | let operation = |external: &str| { |
| 1211 | graph.nodes.iter().find(|node| { |
| 1212 | node.binding |
| 1213 | .as_ref() |
| 1214 | .is_some_and(|binding| binding.external == external) |
| 1215 | }) |
| 1216 | }; |
| 1217 | assert_eq!( |
| 1218 | operation("shell:shell_spawn_failure").map(|node| node.state), |
| 1219 | Some(crate::work_graph::NodeState::Failed), |
| 1220 | "dropping an armed spawn guard must terminalize pre-spawn failure" |
| 1221 | ); |
| 1222 | let silent = operation("shell:shell_silent").expect("silent shell operation"); |
| 1223 | assert_eq!(silent.state, crate::work_graph::NodeState::Active); |
| 1224 | let observation = silent |
| 1225 | .binding |
| 1226 | .as_ref() |
| 1227 | .and_then(|binding| binding.last_observation.as_ref()) |
| 1228 | .expect("last shell observation"); |
| 1229 | assert_eq!(observation.seq, 2); |
| 1230 | assert_eq!( |
| 1231 | observation |
| 1232 | .output |
| 1233 | .as_ref() |
| 1234 | .and_then(crate::work_graph::EvidenceRef::raw_bytes), |
| 1235 | Some(512) |
| 1236 | ); |
| 1237 | } |
| 1238 | |
| 1239 | #[test] |
| 1240 | fn exec_shell_parallel_flags_are_input_aware() { |
| 1241 | let tool = BashTool::new("Bash"); |
| 1242 | let readonly = json!({"command": "git status -s"}); |
| 1243 | assert!(tool.supports_parallel_for(&readonly)); |
| 1244 | assert!(tool.is_read_only_for(&readonly)); |
| 1245 | assert_eq!( |
| 1246 | tool.approval_requirement_for(&readonly), |
| 1247 | ApprovalRequirement::Auto |
| 1248 | ); |
| 1249 | |
| 1250 | for input in [ |
| 1251 | json!({"command": "fd -e rs ."}), |
| 1252 | json!({"command": "fd -H --type f src"}), |
| 1253 | json!({"command": "git grep TODO crates/engine/src/tools"}), |
| 1254 | json!({"action": "run", "command": "gh issue list --limit 10"}), |
| 1255 | json!({"action": "run", "command": "gh issue view 5287"}), |
| 1256 | ] { |
| 1257 | assert!(tool.supports_parallel_for(&input), "{input:?}"); |
| 1258 | assert!(tool.is_read_only_for(&input), "{input:?}"); |
| 1259 | assert_eq!( |
| 1260 | tool.approval_requirement_for(&input), |
| 1261 | ApprovalRequirement::Auto, |
| 1262 | "{input:?}" |
| 1263 | ); |
| 1264 | } |
| 1265 | |
| 1266 | for input in [ |
| 1267 | json!({"command": "git status -s", "background": true}), |
| 1268 | json!({"command": "git status -s", "background": "false"}), |
| 1269 | json!({"command": "git status -s", "stdin": ""}), |
| 1270 | json!({"action": "wait", "command": "pwd", "task_id": "shell_1"}), |
| 1271 | json!({"action": "interact", "command": "pwd", "task_id": "shell_1"}), |
| 1272 | json!({"action": "cancel", "command": "pwd", "task_id": "shell_1"}), |
| 1273 | json!({"action": 3, "command": "pwd"}), |
| 1274 | json!({"command": "pwd", "unexpected": true}), |
| 1275 | json!({"command": "cargo build"}), |
| 1276 | json!({"command": "bash -lc 'git status'"}), |
| 1277 | json!({"command": "sh -c 'rg TODO crates'"}), |
| 1278 | json!({"command": "PAGER=./pwn.sh git log"}), |
| 1279 | json!({"command": "GH_PAGER=./pwn.sh gh issue view 5287"}), |
| 1280 | json!({"command": "rg ${9:---pre=./repo-script} needle ."}), |
| 1281 | json!({"command": "rg ${9:---hostname-bin=./repo-script} needle ."}), |
| 1282 | json!({"command": "fd ${9:---exec} ./repo-script"}), |
| 1283 | json!({"command": "rg $PATTERN ."}), |
| 1284 | json!({"command": "rg *.rs ."}), |
| 1285 | json!({"command": "bash -lc 'rg TODO crates | head'"}), |
| 1286 | json!({"command": "fd -x ./pwn.sh"}), |
| 1287 | json!({"command": "fd --exec ./pwn.sh"}), |
| 1288 | json!({"command": "fd -uHtx ./pwn.sh"}), |
| 1289 | json!({"command": "rg --pre /tmp/evil.sh needle ."}), |
| 1290 | json!({"command": "rg --hostname-bin ./repo-script --hyperlink-format=file://{host}{path} needle ."}), |
| 1291 | json!({"command": "rg --search-zip needle ."}), |
| 1292 | json!({"command": "rg -z needle ."}), |
| 1293 | json!({"command": "git grep -O needle"}), |
| 1294 | json!({"command": "git grep -nO needle"}), |
| 1295 | json!({"command": "git grep --textconv needle"}), |
| 1296 | json!({"command": "git diff --ext-diff HEAD"}), |
| 1297 | json!({"command": "git diff --textconv HEAD"}), |
| 1298 | json!({"command": "git log --show-signature -1"}), |
| 1299 | json!({"command": "git show --format=%GS HEAD"}), |
| 1300 | json!({"command": "gh issue close 5287"}), |
| 1301 | json!({"command": "gh issue view 5287 > issue.txt"}), |
| 1302 | json!({"command": "gh pr checks 42 --watch"}), |
| 1303 | json!({"command": "gh issue view 5287 -R git.example.com/o/r"}), |
| 1304 | ] { |
| 1305 | assert!(!tool.supports_parallel_for(&input), "{input:?}"); |
| 1306 | assert!(!tool.is_read_only_for(&input), "{input:?}"); |
| 1307 | assert_eq!( |
| 1308 | tool.approval_requirement_for(&input), |
| 1309 | ApprovalRequirement::Required, |
| 1310 | "{input:?}" |
| 1311 | ); |
| 1312 | } |
| 1313 | |
| 1314 | assert!(tool.starts_detached_for(&json!({ |
| 1315 | "command": "cargo check --workspace", |
| 1316 | "background": true |
| 1317 | }))); |
| 1318 | assert!(tool.starts_detached_for(&json!({ |
| 1319 | "command": "cargo test -p codewhale-tui --bins", |
| 1320 | "tty": true |
| 1321 | }))); |
| 1322 | assert!(!tool.starts_detached_for(&json!({ |
| 1323 | "command": "cargo check --workspace" |
| 1324 | }))); |
| 1325 | assert!(!tool.starts_detached_for(&json!({ |
| 1326 | "command": "cargo check --workspace", |
| 1327 | "background": true, |
| 1328 | "interactive": true |
| 1329 | }))); |
| 1330 | } |
| 1331 | |
| 1332 | #[tokio::test] |
| 1333 | async fn readonly_shell_refuses_raw_string_external_backend() { |
| 1334 | struct Backend(std::sync::atomic::AtomicBool); |
| 1335 | #[async_trait::async_trait] |
| 1336 | impl codewhale_sandbox::backend::SandboxBackend for Backend { |
| 1337 | fn kind(&self) -> codewhale_sandbox::backend::SandboxKind { |
| 1338 | codewhale_sandbox::backend::SandboxKind::OpenSandbox |
| 1339 | } |
| 1340 | async fn exec( |
| 1341 | &self, |
| 1342 | _cmd: &str, |
| 1343 | _env: &std::collections::HashMap<String, String>, |
| 1344 | ) -> anyhow::Result<codewhale_sandbox::backend::SandboxOutput> { |
| 1345 | self.0.store(true, std::sync::atomic::Ordering::SeqCst); |
| 1346 | Ok(codewhale_sandbox::backend::SandboxOutput { |
| 1347 | stdout: String::new(), |
| 1348 | stderr: String::new(), |
| 1349 | exit_code: 0, |
| 1350 | }) |
| 1351 | } |
| 1352 | } |
| 1353 | |
| 1354 | let tmp = tempdir().expect("tempdir"); |
| 1355 | let backend = std::sync::Arc::new(Backend(std::sync::atomic::AtomicBool::new(false))); |
| 1356 | let mut context = ToolContext::new(tmp.path().to_path_buf()) |
| 1357 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1358 | context.sandbox_backend = Some(backend.clone()); |
| 1359 | let error = BashTool::read_only("Bash") |
| 1360 | .execute(json!({"action": "run", "command": "pwd"}), &context) |
| 1361 | .await |
| 1362 | .expect_err("raw-string backend must not receive a classifier-approved argv") |
| 1363 | .to_string(); |
| 1364 | assert!(error.contains("raw command string"), "{error}"); |
| 1365 | assert!(!backend.0.load(std::sync::atomic::Ordering::SeqCst)); |
| 1366 | } |
| 1367 | |
| 1368 | #[tokio::test] |
| 1369 | async fn lowercase_bash_refuses_non_streaming_external_backend() { |
| 1370 | struct Backend(std::sync::atomic::AtomicBool); |
| 1371 | #[async_trait::async_trait] |
| 1372 | impl codewhale_sandbox::backend::SandboxBackend for Backend { |
| 1373 | fn kind(&self) -> codewhale_sandbox::backend::SandboxKind { |
| 1374 | codewhale_sandbox::backend::SandboxKind::OpenSandbox |
| 1375 | } |
| 1376 | async fn exec( |
| 1377 | &self, |
| 1378 | _cmd: &str, |
| 1379 | _env: &std::collections::HashMap<String, String>, |
| 1380 | ) -> anyhow::Result<codewhale_sandbox::backend::SandboxOutput> { |
| 1381 | self.0.store(true, std::sync::atomic::Ordering::SeqCst); |
| 1382 | unreachable!("lowercase bash must fail before external dispatch") |
| 1383 | } |
| 1384 | } |
| 1385 | |
| 1386 | let workspace = tempdir().expect("workspace"); |
| 1387 | let backend = std::sync::Arc::new(Backend(std::sync::atomic::AtomicBool::new(false))); |
| 1388 | let mut context = ToolContext::new(workspace.path()); |
| 1389 | context.sandbox_backend = Some(backend.clone()); |
| 1390 | let error = LowercaseBashTool |
| 1391 | .execute(json!({"command": "pwd", "timeout": 1}), &context) |
| 1392 | .await |
| 1393 | .expect_err("non-streaming backend must be rejected"); |
| 1394 | assert!(error.to_string().contains("combined streaming output")); |
| 1395 | assert!(!backend.0.load(std::sync::atomic::Ordering::SeqCst)); |
| 1396 | } |
| 1397 | |
| 1398 | #[test] |
| 1399 | fn readonly_argv_is_shell_free_and_disables_git_helpers() { |
| 1400 | let (program, args) = hardened_readonly_argv("git show HEAD").expect("argv"); |
| 1401 | assert_eq!(program, "git"); |
| 1402 | assert_eq!( |
| 1403 | &args[..6], |
| 1404 | [ |
| 1405 | "show", |
| 1406 | "--no-ext-diff", |
| 1407 | "--no-textconv", |
| 1408 | "--submodule=short", |
| 1409 | "--ignore-submodules=dirty", |
| 1410 | "--no-show-signature" |
| 1411 | ] |
| 1412 | ); |
| 1413 | assert_eq!(args.last().map(String::as_str), Some("HEAD")); |
| 1414 | |
| 1415 | let (_, args) = hardened_readonly_argv("git -C sub blame f.txt").expect("blame argv"); |
| 1416 | assert_eq!(args, ["-C", "sub", "blame", "--no-textconv", "f.txt"]); |
| 1417 | assert_eq!( |
| 1418 | readonly_git_dirs( |
| 1419 | "git -C sub diff | git --no-pager -C /abs status | cat", |
| 1420 | std::path::Path::new("/ws") |
| 1421 | ), |
| 1422 | [ |
| 1423 | std::path::PathBuf::from("/ws/sub"), |
| 1424 | std::path::PathBuf::from("/abs") |
| 1425 | ] |
| 1426 | ); |
| 1427 | // Chains are split like the classifier splits them, so a `git` read |
| 1428 | // after `&&`, `||` or `;` still gets filter overrides. |
| 1429 | assert_eq!( |
| 1430 | readonly_git_dirs( |
| 1431 | "pwd && git diff; ls || git -C sub status", |
| 1432 | std::path::Path::new("/ws") |
| 1433 | ), |
| 1434 | [ |
| 1435 | std::path::PathBuf::from("/ws"), |
| 1436 | std::path::PathBuf::from("/ws/sub") |
| 1437 | ] |
| 1438 | ); |
| 1439 | |
| 1440 | let (program, args) = hardened_readonly_argv("rg $PATTERN .").expect("literal argv"); |
| 1441 | assert_eq!(program, "rg"); |
| 1442 | assert_eq!(args, ["$PATTERN", "."]); |
| 1443 | } |
| 1444 | |
| 1445 | /// Classifier-approved working-tree reads must not run the repository's clean |
| 1446 | /// filter or textconv driver. The helpers print a sentinel instead of the |
| 1447 | /// content, so this holds whether or not a kernel sandbox blocks their writes. |
| 1448 | #[cfg(unix)] |
| 1449 | #[tokio::test] |
| 1450 | async fn readonly_git_reads_run_no_clean_filter_or_textconv() { |
| 1451 | use codewhale_dependencies::ExternalTool as _; |
| 1452 | use std::os::unix::fs::PermissionsExt as _; |
| 1453 | let workspace = tempdir().expect("workspace"); |
| 1454 | let outside = tempdir().expect("outside"); |
| 1455 | let helper = outside.path().join("helper.sh"); |
| 1456 | std::fs::write(&helper, "#!/bin/sh\necho HELPER-RAN\n").expect("helper"); |
| 1457 | std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).expect("chmod"); |
| 1458 | let helper = helper.display().to_string(); |
| 1459 | let repo = workspace.path(); |
| 1460 | let git = |args: &[&str]| { |
| 1461 | let status = codewhale_dependencies::Git::status(args, repo).expect("git should spawn"); |
| 1462 | assert!(status.success(), "git {args:?} failed"); |
| 1463 | }; |
| 1464 | git(&["init", "-q"]); |
| 1465 | git(&["config", "user.email", "t@example.com"]); |
| 1466 | git(&["config", "user.name", "Test"]); |
| 1467 | git(&["config", "commit.gpgsign", "false"]); |
| 1468 | std::fs::write(repo.join(".gitattributes"), "c.txt filter=x diff=conv\n").expect("attrs"); |
| 1469 | std::fs::write(repo.join("c.txt"), "c1\n").expect("write"); |
| 1470 | git(&["add", "."]); |
| 1471 | git(&["commit", "-q", "-m", "init"]); |
| 1472 | git(&["config", "filter.x.clean", &helper]); |
| 1473 | git(&["config", "diff.conv.textconv", &helper]); |
| 1474 | std::fs::write(repo.join("c.txt"), "c2\n").expect("modify"); |
| 1475 | |
| 1476 | let ctx = ToolContext::new(repo) |
| 1477 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1478 | let tool = BashTool::new("Bash"); |
| 1479 | for command in ["git diff", "git blame c.txt"] { |
| 1480 | let result = tool |
| 1481 | .execute(json!({"command": command}), &ctx) |
| 1482 | .await |
| 1483 | .expect(command); |
| 1484 | assert!(result.success, "{command}: {}", result.content); |
| 1485 | assert!( |
| 1486 | !result.content.contains("HELPER-RAN"), |
| 1487 | "{command} ran a repository-configured command: {}", |
| 1488 | result.content |
| 1489 | ); |
| 1490 | assert!( |
| 1491 | result.content.contains("c2"), |
| 1492 | "{command}: {}", |
| 1493 | result.content |
| 1494 | ); |
| 1495 | } |
| 1496 | } |
| 1497 | |
| 1498 | #[cfg(any(unix, windows))] |
| 1499 | #[test] |
| 1500 | fn readonly_program_resolution_ignores_workspace_shadow_executables() { |
| 1501 | let workspace = tempdir().expect("workspace"); |
| 1502 | let trusted = tempdir().expect("trusted bin"); |
| 1503 | let path = std::env::join_paths([workspace.path(), trusted.path()]).expect("test PATH"); |
| 1504 | |
| 1505 | for program in ["git", "gh", "rg"] { |
| 1506 | let file = if cfg!(windows) { |
| 1507 | format!("{program}.exe") |
| 1508 | } else { |
| 1509 | program.to_string() |
| 1510 | }; |
| 1511 | for directory in [workspace.path(), trusted.path()] { |
| 1512 | let executable = directory.join(&file); |
| 1513 | std::fs::write(&executable, b"fixture").expect("fixture executable"); |
| 1514 | #[cfg(unix)] |
| 1515 | { |
| 1516 | use std::os::unix::fs::PermissionsExt as _; |
| 1517 | let mut permissions = executable.metadata().unwrap().permissions(); |
| 1518 | permissions.set_mode(0o755); |
| 1519 | std::fs::set_permissions(&executable, permissions).unwrap(); |
| 1520 | } |
| 1521 | } |
| 1522 | let resolved = |
| 1523 | resolve_readonly_program_from_path(program, workspace.path(), &path).expect("resolved"); |
| 1524 | assert_eq!(resolved, trusted.path().join(file).canonicalize().unwrap()); |
| 1525 | assert!(resolved.is_absolute() && !resolved.starts_with(workspace.path())); |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | #[test] |
| 1530 | fn readonly_child_env_removes_git_and_github_redirects() { |
| 1531 | let mut command = std::process::Command::new("unused"); |
| 1532 | let redirects = [ |
| 1533 | "GIT_DIR", |
| 1534 | "GIT_COMMON_DIR", |
| 1535 | "GIT_EXEC_PATH", |
| 1536 | "GIT_OBJECT_DIRECTORY", |
| 1537 | "GIT_SSH_COMMAND", |
| 1538 | "GH_CONFIG_DIR", |
| 1539 | "GH_OTHER_PATH", |
| 1540 | ]; |
| 1541 | for key in redirects { |
| 1542 | command.env(key, "outside"); |
| 1543 | } |
| 1544 | command.env(READONLY_ENV_MARKER, "1"); |
| 1545 | let env = HashMap::from([(READONLY_ENV_MARKER.to_string(), "1".to_string())]); |
| 1546 | remove_readonly_redirect_env(&mut command, &env); |
| 1547 | for key in redirects { |
| 1548 | assert!( |
| 1549 | command |
| 1550 | .get_envs() |
| 1551 | .any(|(name, value)| name == std::ffi::OsStr::new(key) && value.is_none()), |
| 1552 | "{key} must be removed from the child environment" |
| 1553 | ); |
| 1554 | } |
| 1555 | assert!( |
| 1556 | command |
| 1557 | .get_envs() |
| 1558 | .any(|(name, value)| name == READONLY_ENV_MARKER && value.is_none()) |
| 1559 | ); |
| 1560 | } |
| 1561 | |
| 1562 | #[test] |
| 1563 | fn readonly_operands_are_workspace_bounded_and_symlink_aware() { |
| 1564 | let workspace = tempdir().expect("workspace"); |
| 1565 | let outside = tempdir().expect("outside"); |
| 1566 | std::fs::write(workspace.path().join("inside.txt"), "inside").expect("inside file"); |
| 1567 | std::fs::write(outside.path().join("secret.txt"), "secret").expect("outside file"); |
| 1568 | |
| 1569 | enforce_readonly_workspace_operands("cat inside.txt", workspace.path(), workspace.path()) |
| 1570 | .expect("in-workspace operand"); |
| 1571 | let inside_absolute = workspace |
| 1572 | .path() |
| 1573 | .join("inside.txt") |
| 1574 | .canonicalize() |
| 1575 | .expect("canonical inside file"); |
| 1576 | enforce_readonly_workspace_operands( |
| 1577 | &format!("cat {}", inside_absolute.display()), |
| 1578 | workspace.path(), |
| 1579 | workspace.path(), |
| 1580 | ) |
| 1581 | .expect("absolute in-workspace operand"); |
| 1582 | |
| 1583 | let outside_absolute = outside |
| 1584 | .path() |
| 1585 | .join("secret.txt") |
| 1586 | .canonicalize() |
| 1587 | .expect("canonical outside file"); |
| 1588 | let error = enforce_readonly_workspace_operands( |
| 1589 | &format!("cat {}", outside_absolute.display()), |
| 1590 | workspace.path(), |
| 1591 | workspace.path(), |
| 1592 | ) |
| 1593 | .expect_err("absolute outside operand must fail") |
| 1594 | .to_string(); |
| 1595 | assert!(error.contains("operand.outside_workspace"), "{error}"); |
| 1596 | |
| 1597 | for command in [ |
| 1598 | "cat ../secret.txt", |
| 1599 | "cat ~/.ssh/id_rsa", |
| 1600 | "cat /rooted-current-drive.txt", |
| 1601 | "cat C:secret", |
| 1602 | r"cat C:\secret", |
| 1603 | r"cat \\server\share\secret", |
| 1604 | ] { |
| 1605 | let error = |
| 1606 | enforce_readonly_workspace_operands(command, workspace.path(), workspace.path()) |
| 1607 | .expect_err("out-of-workspace operand must fail") |
| 1608 | .to_string(); |
| 1609 | assert!(error.contains("inside the workspace"), "{command}: {error}"); |
| 1610 | } |
| 1611 | |
| 1612 | #[cfg(unix)] |
| 1613 | { |
| 1614 | std::os::unix::fs::symlink( |
| 1615 | outside.path().join("secret.txt"), |
| 1616 | workspace.path().join("secret-link"), |
| 1617 | ) |
| 1618 | .expect("outside symlink"); |
| 1619 | let error = enforce_readonly_workspace_operands( |
| 1620 | "cat secret-link", |
| 1621 | workspace.path(), |
| 1622 | workspace.path(), |
| 1623 | ) |
| 1624 | .expect_err("symlink escape must fail") |
| 1625 | .to_string(); |
| 1626 | assert!(error.contains("resolves outside"), "{error}"); |
| 1627 | |
| 1628 | let subdir = workspace.path().join("subdir"); |
| 1629 | std::fs::create_dir(&subdir).expect("subdir"); |
| 1630 | std::os::unix::fs::symlink( |
| 1631 | outside.path().join("secret.txt"), |
| 1632 | subdir.join("secret-link"), |
| 1633 | ) |
| 1634 | .expect("cwd-relative outside symlink"); |
| 1635 | enforce_readonly_workspace_operands("cat secret-link", workspace.path(), &subdir) |
| 1636 | .expect_err("operands must resolve relative to the effective cwd"); |
| 1637 | } |
| 1638 | } |
| 1639 | |
| 1640 | #[test] |
| 1641 | fn windows_verbatim_and_drive_operands_survive_posix_split() { |
| 1642 | // `shell_words` splits with POSIX backslash-escaping, which silently eats |
| 1643 | // the separators of Windows absolute paths (`C:\Users\...` becomes |
| 1644 | // `C:Users...`) and mangles the `\\?\` verbatim prefix before operand |
| 1645 | // classification can see it. The protection doubles those backslashes so |
| 1646 | // the splitter round-trips the real path (the `\\?\` cases that the |
| 1647 | // verbatim strip alone could never reach). |
| 1648 | for (raw, expected) in [ |
| 1649 | (r"\\?\C:\Users\foo\inside.txt", r"C:\Users\foo\inside.txt"), |
| 1650 | (r"C:\Users\foo\inside.txt", r"C:\Users\foo\inside.txt"), |
| 1651 | (r"\\server\share\secret", r"\\server\share\secret"), |
| 1652 | (r"\\.\device\path", r"\\.\device\path"), |
| 1653 | ] { |
| 1654 | let protected = normalize_windows_command_paths(&format!("cat {raw}")); |
| 1655 | let argv = shell_words::split(&protected).expect("split must succeed"); |
| 1656 | assert_eq!( |
| 1657 | argv, |
| 1658 | vec!["cat".to_string(), expected.to_string()], |
| 1659 | "{raw} must survive the POSIX split" |
| 1660 | ); |
| 1661 | } |
| 1662 | } |
| 1663 | |
| 1664 | #[test] |
| 1665 | fn windows_path_protection_leaves_other_words_untouched() { |
| 1666 | // POSIX escapes, drive-relative spellings, and plain relative operands |
| 1667 | // are not Windows absolute paths and must round-trip unchanged. |
| 1668 | assert_eq!( |
| 1669 | normalize_windows_command_paths("echo a\\ b && cat inside.txt"), |
| 1670 | "echo a\\ b && cat inside.txt" |
| 1671 | ); |
| 1672 | assert_eq!( |
| 1673 | normalize_windows_command_paths("cat C:secret"), |
| 1674 | "cat C:secret" |
| 1675 | ); |
| 1676 | assert_eq!( |
| 1677 | normalize_windows_command_paths("cat inside.txt"), |
| 1678 | "cat inside.txt" |
| 1679 | ); |
| 1680 | } |
| 1681 | |
| 1682 | #[test] |
| 1683 | fn readonly_github_shell_calls_obey_the_host_network_policy_before_spawn() { |
| 1684 | let tmp = tempdir().expect("tempdir"); |
| 1685 | let context = |default| { |
| 1686 | ToolContext::new(tmp.path()).with_network_policy( |
| 1687 | codewhale_net::network_policy::NetworkPolicyDecider::new( |
| 1688 | codewhale_net::network_policy::NetworkPolicy { |
| 1689 | default, |
| 1690 | ..codewhale_net::network_policy::NetworkPolicy::default() |
| 1691 | }, |
| 1692 | None, |
| 1693 | ), |
| 1694 | ) |
| 1695 | }; |
| 1696 | |
| 1697 | let allow = context(codewhale_net::network_policy::DecisionToml::Allow); |
| 1698 | enforce_readonly_network_reads("gh issue view 5287", &allow) |
| 1699 | .expect("allowed github.com policy"); |
| 1700 | |
| 1701 | let deny = context(codewhale_net::network_policy::DecisionToml::Deny); |
| 1702 | let denied = enforce_readonly_network_reads("gh issue list", &deny) |
| 1703 | .expect_err("deny must stop before spawning gh") |
| 1704 | .to_string(); |
| 1705 | assert!(denied.contains("blocked by the active network policy")); |
| 1706 | enforce_readonly_network_reads("git status", &deny) |
| 1707 | .expect("local reads do not consult the network policy"); |
| 1708 | |
| 1709 | let prompt = context(codewhale_net::network_policy::DecisionToml::Prompt); |
| 1710 | let prompted = enforce_readonly_network_reads("gh issue view 5287", &prompt) |
| 1711 | .expect_err("headless Scout cannot prompt interactively") |
| 1712 | .to_string(); |
| 1713 | assert!(prompted.contains("requires network approval")); |
| 1714 | |
| 1715 | // Read-only agents: every admitted network segment is judged. |
| 1716 | let readonly_deny = context(codewhale_net::network_policy::DecisionToml::Deny) |
| 1717 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1718 | for command in ["gh pr view 1 | head", "ls && gh issue list"] { |
| 1719 | let denied = enforce_readonly_network_reads(command, &readonly_deny) |
| 1720 | .expect_err("a network read inside a composition is still judged") |
| 1721 | .to_string(); |
| 1722 | assert!(denied.contains("blocked"), "{command}: {denied}"); |
| 1723 | } |
| 1724 | // npm is refused by the command authority before a configured registry |
| 1725 | // could be mistaken for the fixed public-registry network label. |
| 1726 | let npm = json!({"command": "npm view x"}); |
| 1727 | let refusal = exec_shell_input_agent_readonly_verdict(&npm).expect_err("npm needs approval"); |
| 1728 | assert!(refusal.detail.contains("configuration")); |
| 1729 | // An ordinary full shell retains its existing policy/approval path. |
| 1730 | enforce_readonly_network_reads("npm view x", &deny) |
| 1731 | .expect("npm is not granted or refused by full-shell read-only detection"); |
| 1732 | // A full shell keeps its historical scope: only a lone gh read. |
| 1733 | enforce_readonly_network_reads("gh pr view 1 | head", &deny) |
| 1734 | .expect("full shell pipelines are governed elsewhere"); |
| 1735 | } |
| 1736 | |
| 1737 | #[test] |
| 1738 | fn exec_shell_interact_requires_approval() { |
| 1739 | let tool = BashTool::alias("exec_shell_interact", "interact"); |
| 1740 | assert_eq!(tool.approval_requirement(), ApprovalRequirement::Required); |
| 1741 | assert!( |
| 1742 | tool.capabilities() |
| 1743 | .contains(&ToolCapability::RequiresApproval) |
| 1744 | ); |
| 1745 | } |
| 1746 | |
| 1747 | #[tokio::test] |
| 1748 | async fn read_only_shell_policy_blocks_non_readonly_commands() { |
| 1749 | let tmp = tempdir().expect("tempdir"); |
| 1750 | let ctx = ToolContext::new(tmp.path()) |
| 1751 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1752 | let tool = BashTool::new("Bash"); |
| 1753 | |
| 1754 | for (input, rule) in [ |
| 1755 | (json!({"command": "cargo build"}), "program:"), |
| 1756 | ( |
| 1757 | json!({"command": "git status -s", "background": true}), |
| 1758 | "shape:", |
| 1759 | ), |
| 1760 | ( |
| 1761 | json!({"command": "git --config-env=core.fsmonitor=SHELL status"}), |
| 1762 | "option:", |
| 1763 | ), |
| 1764 | ( |
| 1765 | json!({"command": "git -cdiff.foo.textconv=./repo-script diff HEAD"}), |
| 1766 | "option:", |
| 1767 | ), |
| 1768 | (json!({"command": "rg -f/etc/passwd needle ."}), "option:"), |
| 1769 | (json!({"command": "touch x && ls"}), "program:"), |
| 1770 | ] { |
| 1771 | // A typed denial, so a Fleet worker's no-progress guard counts it. |
| 1772 | let error = tool |
| 1773 | .execute(input.clone(), &ctx) |
| 1774 | .await |
| 1775 | .expect_err("classifier refusal"); |
| 1776 | assert!( |
| 1777 | matches!(error, ToolError::PermissionDenied { .. }), |
| 1778 | "{input}: {error}" |
| 1779 | ); |
| 1780 | let message = error.to_string(); |
| 1781 | assert!(message.contains("[shell.readonly.command]"), "{message}"); |
| 1782 | assert!(message.contains(rule), "{input}: {message}"); |
| 1783 | } |
| 1784 | assert!(!tmp.path().join("x").exists()); |
| 1785 | } |
| 1786 | |
| 1787 | #[tokio::test] |
| 1788 | async fn read_only_refusal_names_child_alternatives_instead_of_mode_switch() { |
| 1789 | // #6298: a child has no `/mode` to switch to — a refusal that tells it to |
| 1790 | // switch modes is a dead end beside an available absurd path. The child |
| 1791 | // branch must name the child's own alternatives and the escalation path, |
| 1792 | // and only tools a read-only child actually has (#6015). |
| 1793 | let tmp = tempdir().expect("tempdir"); |
| 1794 | let child_ctx = ToolContext::new(tmp.path()) |
| 1795 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly) |
| 1796 | .with_owner_agent("agent_child", "child"); |
| 1797 | let tool = BashTool::new("Bash"); |
| 1798 | let message = tool |
| 1799 | .execute(json!({"command": "touch evil.txt"}), &child_ctx) |
| 1800 | .await |
| 1801 | .expect_err("refused") |
| 1802 | .to_string(); |
| 1803 | let rejection = codewhale_execpolicy::command_safety::agent_readonly_verdict("touch evil.txt") |
| 1804 | .expect_err("touch is not a read"); |
| 1805 | assert!(message.contains(&rejection.to_string()), "{message}"); |
| 1806 | assert!(message.contains("program: `touch`"), "{message}"); |
| 1807 | assert!(message.contains("File tool"), "{message}"); |
| 1808 | assert!( |
| 1809 | message.contains("return your findings and the blocked probe to the parent"), |
| 1810 | "{message}" |
| 1811 | ); |
| 1812 | for absent in ["/mode", "Git", "Run tests", "merge_tree"] { |
| 1813 | assert!(!message.contains(absent), "{absent} in {message}"); |
| 1814 | } |
| 1815 | assert!(!tmp.path().join("evil.txt").exists()); |
| 1816 | |
| 1817 | let parent_ctx = ToolContext::new(tmp.path()) |
| 1818 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1819 | let message = tool |
| 1820 | .execute(json!({"command": "cargo build"}), &parent_ctx) |
| 1821 | .await |
| 1822 | .expect_err("refused") |
| 1823 | .to_string(); |
| 1824 | assert!( |
| 1825 | message.contains("The user can change modes with /mode."), |
| 1826 | "{message}" |
| 1827 | ); |
| 1828 | } |
| 1829 | |
| 1830 | #[test] |
| 1831 | fn leading_cd_moves_into_cwd_for_every_gate() { |
| 1832 | let rewritten = normalize_readonly_cd(&json!({"command": "cd sub && ls"})); |
| 1833 | assert_eq!(rewritten, json!({"command": "ls", "cwd": "sub"})); |
| 1834 | let rewritten = |
| 1835 | normalize_readonly_cd(&json!({"command": "cd inner && git diff", "cwd": "sub"})); |
| 1836 | assert_eq!(rewritten["command"], "git diff"); |
| 1837 | assert_eq!( |
| 1838 | std::path::Path::new(rewritten["cwd"].as_str().unwrap()), |
| 1839 | std::path::Path::new("sub").join("inner") |
| 1840 | ); |
| 1841 | for command in ["cd a; ls", "ls && cd b && ls", "cd && ls", "cd $X && ls"] { |
| 1842 | let input = json!({"command": command}); |
| 1843 | assert_eq!(normalize_readonly_cd(&input), input, "{command}"); |
| 1844 | assert!(!agent_readonly_bash_input(&input), "{command}"); |
| 1845 | } |
| 1846 | // The enforced lane runs its command unchanged. |
| 1847 | let enforced = json!({"command": "cd sub && ls", "read_only": true}); |
| 1848 | assert_eq!(normalize_readonly_cd(&enforced), enforced); |
| 1849 | assert!(agent_readonly_bash_input( |
| 1850 | &json!({"command": "cd sub && ls"}) |
| 1851 | )); |
| 1852 | assert!(agent_readonly_bash_input( |
| 1853 | &json!({"command": "cd sub && git diff && echo '=== FILES ===' && ls -la"}) |
| 1854 | )); |
| 1855 | } |
| 1856 | |
| 1857 | #[cfg(unix)] |
| 1858 | #[tokio::test] |
| 1859 | async fn read_only_shell_runs_chains_and_leading_cd() { |
| 1860 | let workspace = tempdir().expect("workspace"); |
| 1861 | std::fs::create_dir(workspace.path().join("sub")).expect("sub"); |
| 1862 | std::fs::write(workspace.path().join("sub").join("a.txt"), "alpha\n").expect("a"); |
| 1863 | std::fs::write(workspace.path().join("b.txt"), "beta\n").expect("b"); |
| 1864 | let ctx = ToolContext::new(workspace.path()) |
| 1865 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1866 | let tool = BashTool::new("Bash"); |
| 1867 | let result = tool |
| 1868 | .execute(json!({"command": "cd sub && ls"}), &ctx) |
| 1869 | .await |
| 1870 | .expect("cd is moved into cwd"); |
| 1871 | assert!(result.success, "{}", result.content); |
| 1872 | assert!(result.content.contains("a.txt"), "{}", result.content); |
| 1873 | assert!(!result.content.contains("b.txt"), "{}", result.content); |
| 1874 | |
| 1875 | let result = tool |
| 1876 | .execute( |
| 1877 | json!({"command": "cat b.txt && echo --- && cat sub/a.txt 2>/dev/null"}), |
| 1878 | &ctx, |
| 1879 | ) |
| 1880 | .await |
| 1881 | .expect("chain of reads"); |
| 1882 | if !result.success && result.content.contains("require bash or zsh") { |
| 1883 | return; |
| 1884 | } |
| 1885 | assert!(result.success, "{}", result.content); |
| 1886 | assert!(result.content.contains("beta"), "{}", result.content); |
| 1887 | assert!(result.content.contains("---"), "{}", result.content); |
| 1888 | assert!(result.content.contains("alpha"), "{}", result.content); |
| 1889 | |
| 1890 | let error = tool |
| 1891 | .execute(json!({"command": "cd .. && ls"}), &ctx) |
| 1892 | .await |
| 1893 | .expect_err("a cd outside the workspace is refused") |
| 1894 | .to_string(); |
| 1895 | assert!( |
| 1896 | error.contains("escapes workspace") || error.contains("outside_workspace"), |
| 1897 | "{error}" |
| 1898 | ); |
| 1899 | } |
| 1900 | |
| 1901 | #[cfg(unix)] |
| 1902 | #[tokio::test] |
| 1903 | async fn read_only_operand_checks_apply_to_every_segment() { |
| 1904 | let workspace = tempdir().expect("workspace"); |
| 1905 | let ctx = ToolContext::new(workspace.path()) |
| 1906 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1907 | let error = BashTool::new("Bash") |
| 1908 | .execute(json!({"command": "gh pr view 1 && cat /etc/passwd"}), &ctx) |
| 1909 | .await |
| 1910 | .expect_err("the gh exemption covers only the gh segment"); |
| 1911 | assert!( |
| 1912 | error.to_string().contains("shell.readonly.operand"), |
| 1913 | "{error}" |
| 1914 | ); |
| 1915 | } |
| 1916 | |
| 1917 | #[cfg(unix)] |
| 1918 | #[tokio::test] |
| 1919 | async fn read_only_shell_resolves_operands_from_the_effective_cwd() { |
| 1920 | let workspace = tempdir().expect("workspace"); |
| 1921 | let outside = tempdir().expect("outside"); |
| 1922 | let subdir = workspace.path().join("subdir"); |
| 1923 | std::fs::create_dir(&subdir).expect("subdir"); |
| 1924 | std::fs::write(outside.path().join("secret"), "secret").expect("outside secret"); |
| 1925 | std::os::unix::fs::symlink(outside.path().join("secret"), subdir.join("secret-link")) |
| 1926 | .expect("symlink"); |
| 1927 | let ctx = ToolContext::new(workspace.path()) |
| 1928 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1929 | let error = BashTool::new("Bash") |
| 1930 | .execute( |
| 1931 | json!({"action": "run", "command": "cat secret-link", "cwd": "subdir"}), |
| 1932 | &ctx, |
| 1933 | ) |
| 1934 | .await |
| 1935 | .expect_err("cwd-relative symlink escape must fail before spawn") |
| 1936 | .to_string(); |
| 1937 | assert!(error.contains("resolves outside"), "{error}"); |
| 1938 | } |
| 1939 | |
| 1940 | #[cfg(unix)] |
| 1941 | #[tokio::test] |
| 1942 | async fn read_only_shell_skips_shell_env_hooks() { |
| 1943 | let tmp = tempdir().expect("tempdir"); |
| 1944 | let marker = tmp.path().join("hook-ran"); |
| 1945 | let hook = codewhale_config::hooks::Hook::new( |
| 1946 | codewhale_config::hooks::HookEvent::ShellEnv, |
| 1947 | &format!("printf hit > '{}'", marker.display()), |
| 1948 | ); |
| 1949 | let executor = crate::hooks::HookExecutor::new( |
| 1950 | codewhale_config::hooks::HooksConfig { |
| 1951 | enabled: true, |
| 1952 | hooks: vec![hook], |
| 1953 | ..codewhale_config::hooks::HooksConfig::default() |
| 1954 | }, |
| 1955 | tmp.path().to_path_buf(), |
| 1956 | ); |
| 1957 | let mut context = ToolContext::new(tmp.path()) |
| 1958 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1959 | context.runtime.hook_executor = Some(std::sync::Arc::new(executor)); |
| 1960 | |
| 1961 | let result = BashTool::read_only("Bash") |
| 1962 | .execute(json!({"command": "pwd"}), &context) |
| 1963 | .await |
| 1964 | .expect("read-only inspection"); |
| 1965 | assert!(result.success, "{}", result.content); |
| 1966 | assert!(!marker.exists(), "shell_env hook must not run for ReadOnly"); |
| 1967 | } |
| 1968 | |
| 1969 | #[tokio::test] |
| 1970 | async fn read_only_shell_policy_allows_readonly_inspection() { |
| 1971 | let tmp = tempdir().expect("tempdir"); |
| 1972 | let ctx = ToolContext::new(tmp.path()) |
| 1973 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 1974 | |
| 1975 | let result = BashTool::new("Bash") |
| 1976 | .execute(json!({"command": "pwd"}), &ctx) |
| 1977 | .await |
| 1978 | .expect("execute"); |
| 1979 | |
| 1980 | assert!( |
| 1981 | result.success, |
| 1982 | "unexpected shell failure: {}", |
| 1983 | result.content |
| 1984 | ); |
| 1985 | assert_eq!( |
| 1986 | result |
| 1987 | .metadata |
| 1988 | .as_ref() |
| 1989 | .and_then(|metadata| metadata.get("status")) |
| 1990 | .and_then(Value::as_str), |
| 1991 | Some("Completed") |
| 1992 | ); |
| 1993 | } |
| 1994 | |
| 1995 | #[tokio::test] |
| 1996 | async fn exec_shell_multiline_block_explains_allow_shell_boundary() { |
| 1997 | let tmp = tempdir().expect("tempdir"); |
| 1998 | let ctx = ToolContext::new(tmp.path()); |
| 1999 | |
| 2000 | let result = BashTool::new("Bash") |
| 2001 | .execute( |
| 2002 | json!({"command": "python3 -c \"print(1)\nprint(2)\""}), |
| 2003 | &ctx, |
| 2004 | ) |
| 2005 | .await |
| 2006 | .expect("execute"); |
| 2007 | |
| 2008 | assert!(!result.success); |
| 2009 | assert!(result.content.contains("Command contains multiple lines")); |
| 2010 | assert!( |
| 2011 | result |
| 2012 | .content |
| 2013 | .contains("allow_shell=true exposes shell tools"), |
| 2014 | "{}", |
| 2015 | result.content |
| 2016 | ); |
| 2017 | assert!( |
| 2018 | result |
| 2019 | .content |
| 2020 | .contains("Write multiline scripts to a file first"), |
| 2021 | "{}", |
| 2022 | result.content |
| 2023 | ); |
| 2024 | assert!( |
| 2025 | result.content.contains("background=true"), |
| 2026 | "{}", |
| 2027 | result.content |
| 2028 | ); |
| 2029 | } |
| 2030 | |
| 2031 | #[test] |
| 2032 | fn exec_shell_wait_schema_defaults_to_blocking() { |
| 2033 | let schema = BashTool::alias("exec_shell_wait", "wait").input_schema(); |
| 2034 | assert!( |
| 2035 | schema["properties"]["wait"]["description"] |
| 2036 | .as_str() |
| 2037 | .is_some_and(|description| description.contains("default: true")) |
| 2038 | ); |
| 2039 | assert!( |
| 2040 | BashTool::alias("exec_shell_wait", "wait") |
| 2041 | .description() |
| 2042 | .contains("wait") |
| 2043 | ); |
| 2044 | } |
| 2045 | |
| 2046 | #[tokio::test] |
| 2047 | async fn exec_shell_wait_without_wait_arg_blocks_until_completion() { |
| 2048 | let tmp = tempdir().expect("tempdir"); |
| 2049 | let ctx = ToolContext::new(tmp.path()); |
| 2050 | let start_result = BashTool::new("Bash") |
| 2051 | .execute( |
| 2052 | json!({"command": sleep_command(1), "background": true}), |
| 2053 | &ctx, |
| 2054 | ) |
| 2055 | .await |
| 2056 | .expect("start background"); |
| 2057 | let task_id = start_result |
| 2058 | .metadata |
| 2059 | .as_ref() |
| 2060 | .and_then(|metadata| metadata.get("task_id")) |
| 2061 | .and_then(Value::as_str) |
| 2062 | .expect("task id") |
| 2063 | .to_string(); |
| 2064 | |
| 2065 | let wait_result = BashTool::new("Bash") |
| 2066 | .execute( |
| 2067 | json!({"action": "wait", "task_id": task_id, "timeout_ms": 5_000}), |
| 2068 | &ctx, |
| 2069 | ) |
| 2070 | .await |
| 2071 | .expect("wait for completion"); |
| 2072 | |
| 2073 | assert_eq!( |
| 2074 | wait_result |
| 2075 | .metadata |
| 2076 | .as_ref() |
| 2077 | .and_then(|metadata| metadata.get("status")) |
| 2078 | .and_then(Value::as_str), |
| 2079 | Some("Completed") |
| 2080 | ); |
| 2081 | } |
| 2082 | |
| 2083 | #[tokio::test] |
| 2084 | async fn exec_shell_wait_false_returns_nonblocking_snapshot() { |
| 2085 | let tmp = tempdir().expect("tempdir"); |
| 2086 | let ctx = ToolContext::new(tmp.path()); |
| 2087 | let start_result = BashTool::new("Bash") |
| 2088 | .execute( |
| 2089 | json!({"command": sleep_command(2), "background": true}), |
| 2090 | &ctx, |
| 2091 | ) |
| 2092 | .await |
| 2093 | .expect("start background"); |
| 2094 | let task_id = start_result |
| 2095 | .metadata |
| 2096 | .as_ref() |
| 2097 | .and_then(|metadata| metadata.get("task_id")) |
| 2098 | .and_then(Value::as_str) |
| 2099 | .expect("task id") |
| 2100 | .to_string(); |
| 2101 | |
| 2102 | let started = Instant::now(); |
| 2103 | let wait_result = BashTool::new("Bash") |
| 2104 | .execute( |
| 2105 | json!({"action": "wait", "task_id": task_id, "timeout_ms": 5_000, "wait": false}), |
| 2106 | &ctx, |
| 2107 | ) |
| 2108 | .await |
| 2109 | .expect("poll snapshot"); |
| 2110 | |
| 2111 | assert!( |
| 2112 | started.elapsed() < Duration::from_millis(1_000), |
| 2113 | "wait=false should return a snapshot without blocking" |
| 2114 | ); |
| 2115 | assert_eq!( |
| 2116 | wait_result |
| 2117 | .metadata |
| 2118 | .as_ref() |
| 2119 | .and_then(|metadata| metadata.get("status")) |
| 2120 | .and_then(Value::as_str), |
| 2121 | Some("Running") |
| 2122 | ); |
| 2123 | } |
| 2124 | |
| 2125 | #[tokio::test] |
| 2126 | async fn exec_shell_wait_without_wait_arg_returns_running_at_timeout() { |
| 2127 | let tmp = tempdir().expect("tempdir"); |
| 2128 | let ctx = ToolContext::new(tmp.path()); |
| 2129 | let start_result = BashTool::new("Bash") |
| 2130 | .execute( |
| 2131 | json!({"command": sleep_command(5), "background": true}), |
| 2132 | &ctx, |
| 2133 | ) |
| 2134 | .await |
| 2135 | .expect("start background"); |
| 2136 | let task_id = start_result |
| 2137 | .metadata |
| 2138 | .as_ref() |
| 2139 | .and_then(|metadata| metadata.get("task_id")) |
| 2140 | .and_then(Value::as_str) |
| 2141 | .expect("task id") |
| 2142 | .to_string(); |
| 2143 | |
| 2144 | let started = Instant::now(); |
| 2145 | let result = BashTool::new("Bash") |
| 2146 | .execute( |
| 2147 | json!({"action": "wait", "task_id": task_id, "timeout_ms": 1_000}), |
| 2148 | &ctx, |
| 2149 | ) |
| 2150 | .await |
| 2151 | .expect("bounded wait"); |
| 2152 | assert!(started.elapsed() >= Duration::from_millis(900)); |
| 2153 | assert!(started.elapsed() < Duration::from_secs(3)); |
| 2154 | assert_eq!( |
| 2155 | result |
| 2156 | .metadata |
| 2157 | .as_ref() |
| 2158 | .and_then(|metadata| metadata.get("status")) |
| 2159 | .and_then(Value::as_str), |
| 2160 | Some("Running") |
| 2161 | ); |
| 2162 | |
| 2163 | BashTool::new("Bash") |
| 2164 | .execute(json!({"action": "cancel", "task_id": task_id}), &ctx) |
| 2165 | .await |
| 2166 | .expect("cancel background"); |
| 2167 | } |
| 2168 | |
| 2169 | #[tokio::test] |
| 2170 | async fn exec_shell_wait_many_until_any_returns_when_the_first_task_settles() { |
| 2171 | let tmp = tempdir().expect("tempdir"); |
| 2172 | let ctx = ToolContext::new(tmp.path()); |
| 2173 | let short = BashTool::new("Bash") |
| 2174 | .execute( |
| 2175 | json!({"command": sleep_command(1), "background": true}), |
| 2176 | &ctx, |
| 2177 | ) |
| 2178 | .await |
| 2179 | .expect("start short"); |
| 2180 | let long = BashTool::new("Bash") |
| 2181 | .execute( |
| 2182 | json!({"command": sleep_command(30), "background": true}), |
| 2183 | &ctx, |
| 2184 | ) |
| 2185 | .await |
| 2186 | .expect("start long"); |
| 2187 | let short_id = short |
| 2188 | .metadata |
| 2189 | .as_ref() |
| 2190 | .and_then(|m| m.get("task_id")) |
| 2191 | .and_then(Value::as_str) |
| 2192 | .expect("short id") |
| 2193 | .to_string(); |
| 2194 | let long_id = long |
| 2195 | .metadata |
| 2196 | .as_ref() |
| 2197 | .and_then(|m| m.get("task_id")) |
| 2198 | .and_then(Value::as_str) |
| 2199 | .expect("long id") |
| 2200 | .to_string(); |
| 2201 | |
| 2202 | let started = Instant::now(); |
| 2203 | let result = BashTool::new("Bash") |
| 2204 | .execute( |
| 2205 | json!({ |
| 2206 | "action": "wait", |
| 2207 | "task_ids": [short_id, long_id], |
| 2208 | "until": "any", |
| 2209 | "timeout_ms": 8_000 |
| 2210 | }), |
| 2211 | &ctx, |
| 2212 | ) |
| 2213 | .await |
| 2214 | .expect("multi wait"); |
| 2215 | |
| 2216 | assert!( |
| 2217 | started.elapsed() < Duration::from_secs(5), |
| 2218 | "until=any must not wait for the long task" |
| 2219 | ); |
| 2220 | let statuses = result |
| 2221 | .metadata |
| 2222 | .as_ref() |
| 2223 | .expect("metadata") |
| 2224 | .get("statuses") |
| 2225 | .expect("statuses"); |
| 2226 | assert_eq!(statuses[short_id.as_str()], "Completed"); |
| 2227 | assert_eq!(statuses[long_id.as_str()], "Running"); |
| 2228 | assert_eq!( |
| 2229 | result.metadata.as_ref().and_then(|m| m.get("until")), |
| 2230 | Some(&json!("any")) |
| 2231 | ); |
| 2232 | assert_eq!( |
| 2233 | result.metadata.as_ref().and_then(|m| m.get("timed_out")), |
| 2234 | Some(&json!(false)) |
| 2235 | ); |
| 2236 | } |
| 2237 | |
| 2238 | #[tokio::test] |
| 2239 | async fn exec_shell_wait_many_all_reports_timeout_and_still_running() { |
| 2240 | let tmp = tempdir().expect("tempdir"); |
| 2241 | let ctx = ToolContext::new(tmp.path()); |
| 2242 | let first = BashTool::new("Bash") |
| 2243 | .execute( |
| 2244 | json!({"command": sleep_command(30), "background": true}), |
| 2245 | &ctx, |
| 2246 | ) |
| 2247 | .await |
| 2248 | .expect("start first"); |
| 2249 | let second = BashTool::new("Bash") |
| 2250 | .execute( |
| 2251 | json!({"command": sleep_command(30), "background": true}), |
| 2252 | &ctx, |
| 2253 | ) |
| 2254 | .await |
| 2255 | .expect("start second"); |
| 2256 | let first_id = first |
| 2257 | .metadata |
| 2258 | .as_ref() |
| 2259 | .and_then(|m| m.get("task_id")) |
| 2260 | .and_then(Value::as_str) |
| 2261 | .expect("first id") |
| 2262 | .to_string(); |
| 2263 | let second_id = second |
| 2264 | .metadata |
| 2265 | .as_ref() |
| 2266 | .and_then(|m| m.get("task_id")) |
| 2267 | .and_then(Value::as_str) |
| 2268 | .expect("second id") |
| 2269 | .to_string(); |
| 2270 | |
| 2271 | let result = BashTool::new("Bash") |
| 2272 | .execute( |
| 2273 | json!({ "action": "wait", "task_ids": [first_id, second_id], "timeout_ms": 1_500 }), |
| 2274 | &ctx, |
| 2275 | ) |
| 2276 | .await |
| 2277 | .expect("multi wait times out"); |
| 2278 | assert_eq!( |
| 2279 | result.metadata.as_ref().and_then(|m| m.get("timed_out")), |
| 2280 | Some(&json!(true)) |
| 2281 | ); |
| 2282 | assert!(result.content.contains("still running")); |
| 2283 | let statuses = result |
| 2284 | .metadata |
| 2285 | .as_ref() |
| 2286 | .expect("metadata") |
| 2287 | .get("statuses") |
| 2288 | .expect("statuses"); |
| 2289 | assert_eq!(statuses[first_id.as_str()], "Running"); |
| 2290 | assert_eq!(statuses[second_id.as_str()], "Running"); |
| 2291 | } |
| 2292 | |
| 2293 | #[tokio::test] |
| 2294 | async fn exec_shell_wait_many_rejects_an_unknown_task_id() { |
| 2295 | let tmp = tempdir().expect("tempdir"); |
| 2296 | let ctx = ToolContext::new(tmp.path()); |
| 2297 | let err = BashTool::new("Bash") |
| 2298 | .execute( |
| 2299 | json!({ "action": "wait", "task_ids": ["nope-1", "nope-2"], "wait": false }), |
| 2300 | &ctx, |
| 2301 | ) |
| 2302 | .await |
| 2303 | .expect_err("unknown ids must fail the same way as the single-task path"); |
| 2304 | assert!(err.to_string().contains("nope-1"), "{err}"); |
| 2305 | } |
| 2306 | |
| 2307 | #[tokio::test] |
| 2308 | async fn background_start_advertises_task_status_completion() { |
| 2309 | let tmp = tempdir().expect("tempdir"); |
| 2310 | let ctx = ToolContext::new(tmp.path()); |
| 2311 | let result = BashTool::new("Bash") |
| 2312 | .execute( |
| 2313 | json!({"command": sleep_command(1), "background": true}), |
| 2314 | &ctx, |
| 2315 | ) |
| 2316 | .await |
| 2317 | .expect("start background"); |
| 2318 | assert!(result.content.contains("completion is delivered")); |
| 2319 | assert!(result.content.contains("session exits") && result.content.contains("persist=true")); |
| 2320 | let metadata = result.metadata.as_ref().expect("metadata"); |
| 2321 | assert_eq!( |
| 2322 | metadata |
| 2323 | .get("auto_resume_on_completion") |
| 2324 | .and_then(Value::as_bool), |
| 2325 | Some(true) |
| 2326 | ); |
| 2327 | assert_eq!( |
| 2328 | metadata.get("completion_surface").and_then(Value::as_str), |
| 2329 | Some("runtime_event_and_task_status") |
| 2330 | ); |
| 2331 | assert_eq!( |
| 2332 | metadata.get("background_policy").and_then(Value::as_str), |
| 2333 | Some("nonblocking") |
| 2334 | ); |
| 2335 | } |
| 2336 | |
| 2337 | #[tokio::test] |
| 2338 | async fn background_shell_job_preserves_origin_identity() { |
| 2339 | let tmp = tempdir().expect("tempdir"); |
| 2340 | let ctx = ToolContext::new(tmp.path()) |
| 2341 | .with_origin_turn_id("turn-origin") |
| 2342 | .with_origin_tool_call_id("tool-origin") |
| 2343 | .with_owner_agent("agent_owner", "verifier"); |
| 2344 | let result = BashTool::new("Bash") |
| 2345 | .execute( |
| 2346 | json!({"command": sleep_command(2), "background": true}), |
| 2347 | &ctx, |
| 2348 | ) |
| 2349 | .await |
| 2350 | .expect("start owned background shell"); |
| 2351 | |
| 2352 | let metadata = result.metadata.as_ref().expect("metadata"); |
| 2353 | assert_eq!( |
| 2354 | metadata.get("owner_agent_id").and_then(Value::as_str), |
| 2355 | Some("agent_owner") |
| 2356 | ); |
| 2357 | assert_eq!( |
| 2358 | metadata.get("owner_agent_name").and_then(Value::as_str), |
| 2359 | Some("verifier") |
| 2360 | ); |
| 2361 | assert!( |
| 2362 | result |
| 2363 | .content |
| 2364 | .contains("not injected into the parent model"), |
| 2365 | "owned background work must describe its real completion route: {}", |
| 2366 | result.content |
| 2367 | ); |
| 2368 | assert!( |
| 2369 | result.content.contains("`task_shell_wait` directly"), |
| 2370 | "owned background work must name the eager wait tool: {}", |
| 2371 | result.content |
| 2372 | ); |
| 2373 | assert_eq!( |
| 2374 | metadata |
| 2375 | .get("auto_resume_on_completion") |
| 2376 | .and_then(Value::as_bool), |
| 2377 | Some(false) |
| 2378 | ); |
| 2379 | assert_eq!( |
| 2380 | metadata.get("completion_surface").and_then(Value::as_str), |
| 2381 | Some("task_status_and_explicit_wait") |
| 2382 | ); |
| 2383 | let task_id = metadata |
| 2384 | .get("task_id") |
| 2385 | .and_then(Value::as_str) |
| 2386 | .expect("task id") |
| 2387 | .to_string(); |
| 2388 | |
| 2389 | { |
| 2390 | let mut manager = ctx.shell_manager.lock().expect("shell manager"); |
| 2391 | let snapshot = manager |
| 2392 | .list_jobs() |
| 2393 | .into_iter() |
| 2394 | .find(|job| job.id == task_id) |
| 2395 | .expect("owned shell job snapshot"); |
| 2396 | assert_eq!(snapshot.owner_agent_id.as_deref(), Some("agent_owner")); |
| 2397 | assert_eq!(snapshot.owner_agent_name.as_deref(), Some("verifier")); |
| 2398 | assert_eq!(snapshot.origin_tool_call_id.as_deref(), Some("tool-origin")); |
| 2399 | assert_eq!(snapshot.origin_turn_id.as_deref(), Some("turn-origin")); |
| 2400 | let mut legacy_json = serde_json::to_value(&snapshot).expect("serialize snapshot"); |
| 2401 | let legacy_object = legacy_json.as_object_mut().expect("snapshot object"); |
| 2402 | legacy_object.remove("origin_tool_call_id"); |
| 2403 | legacy_object.remove("origin_turn_id"); |
| 2404 | let legacy_snapshot: ShellJobSnapshot = |
| 2405 | serde_json::from_value(legacy_json).expect("deserialize legacy snapshot"); |
| 2406 | assert_eq!(legacy_snapshot.origin_tool_call_id, None); |
| 2407 | assert_eq!(legacy_snapshot.origin_turn_id, None); |
| 2408 | let owners = manager.running_owner_agent_ids(); |
| 2409 | assert_eq!(owners, vec!["agent_owner".to_string()]); |
| 2410 | } |
| 2411 | |
| 2412 | BashTool::alias("exec_shell_cancel", "cancel") |
| 2413 | .execute(json!({"task_id": task_id}), &ctx) |
| 2414 | .await |
| 2415 | .expect("cancel owned background shell"); |
| 2416 | } |
| 2417 | |
| 2418 | #[tokio::test] |
| 2419 | async fn drain_finished_jobs_reports_once() { |
| 2420 | let tmp = tempdir().expect("tempdir"); |
| 2421 | let ctx = ToolContext::new(tmp.path()) |
| 2422 | .with_origin_turn_id("turn-origin") |
| 2423 | .with_origin_tool_call_id("tool-origin"); |
| 2424 | let result = BashTool::new("Bash") |
| 2425 | .execute( |
| 2426 | json!({"command": echo_command("drain-finished-once"), "background": true}), |
| 2427 | &ctx, |
| 2428 | ) |
| 2429 | .await |
| 2430 | .expect("start background"); |
| 2431 | let task_id = result |
| 2432 | .metadata |
| 2433 | .as_ref() |
| 2434 | .and_then(|metadata| metadata.get("task_id")) |
| 2435 | .and_then(Value::as_str) |
| 2436 | .expect("task id") |
| 2437 | .to_string(); |
| 2438 | |
| 2439 | let mut manager = ctx.shell_manager.lock().expect("shell manager"); |
| 2440 | assert!(manager.may_have_undelivered_completion()); |
| 2441 | assert!( |
| 2442 | manager.may_have_undelivered_completion(), |
| 2443 | "read-only detection must not consume the pending completion" |
| 2444 | ); |
| 2445 | let completed = wait_for_completed_shell(&mut manager, &task_id); |
| 2446 | assert_ne!(completed.status, ShellStatus::Running); |
| 2447 | assert!(manager.may_have_undelivered_completion()); |
| 2448 | |
| 2449 | let first = manager |
| 2450 | .drain_finished_jobs_with_evidence() |
| 2451 | .into_iter() |
| 2452 | .map(|completion| completion.event) |
| 2453 | .collect::<Vec<_>>(); |
| 2454 | assert_eq!(first.len(), 1); |
| 2455 | assert_eq!(first[0].task_id, task_id); |
| 2456 | assert_eq!(first[0].status, ShellStatus::Completed); |
| 2457 | assert!(first[0].stdout_tail.contains("drain-finished-once")); |
| 2458 | assert_eq!(first[0].origin_tool_call_id.as_deref(), Some("tool-origin")); |
| 2459 | assert_eq!(first[0].origin_turn_id.as_deref(), Some("turn-origin")); |
| 2460 | let mut legacy_json = serde_json::to_value(&first[0]).expect("serialize completion"); |
| 2461 | let legacy_object = legacy_json.as_object_mut().expect("completion object"); |
| 2462 | legacy_object.remove("origin_tool_call_id"); |
| 2463 | legacy_object.remove("origin_turn_id"); |
| 2464 | let legacy_completion: ShellCompletionEvent = |
| 2465 | serde_json::from_value(legacy_json).expect("deserialize legacy completion"); |
| 2466 | assert_eq!(legacy_completion.origin_tool_call_id, None); |
| 2467 | assert_eq!(legacy_completion.origin_turn_id, None); |
| 2468 | |
| 2469 | let second = manager.drain_finished_jobs_with_evidence(); |
| 2470 | assert!(second.is_empty(), "completion should be reported only once"); |
| 2471 | assert!(!manager.may_have_undelivered_completion()); |
| 2472 | } |
| 2473 | |
| 2474 | #[tokio::test] |
| 2475 | async fn background_job_is_hidden_from_replacement_session_and_resumes_once_for_owner() { |
| 2476 | let tmp = tempdir().expect("tempdir"); |
| 2477 | let ctx_a = ToolContext::new(tmp.path()).with_state_namespace("session-a"); |
| 2478 | let ctx_b = ctx_a.clone().with_state_namespace("session-b"); |
| 2479 | let result = BashTool::new("Bash") |
| 2480 | .execute( |
| 2481 | json!({"command": echo_command("owned-by-a"), "background": true}), |
| 2482 | &ctx_a, |
| 2483 | ) |
| 2484 | .await |
| 2485 | .expect("start A background job"); |
| 2486 | let task_id = result |
| 2487 | .metadata |
| 2488 | .as_ref() |
| 2489 | .and_then(|metadata| metadata.get("task_id")) |
| 2490 | .and_then(Value::as_str) |
| 2491 | .expect("task id") |
| 2492 | .to_string(); |
| 2493 | |
| 2494 | let mut manager = ctx_b.shell_manager.lock().expect("shell manager"); |
| 2495 | assert!(manager.list_jobs_for_session("session-b").is_empty()); |
| 2496 | assert!( |
| 2497 | manager |
| 2498 | .inspect_job_for_session("session-b", &task_id) |
| 2499 | .is_err() |
| 2500 | ); |
| 2501 | assert!( |
| 2502 | manager |
| 2503 | .write_stdin_for_session("session-b", &task_id, "foreign", false) |
| 2504 | .is_err() |
| 2505 | ); |
| 2506 | assert!(manager.kill_for_session("session-b", &task_id).is_err()); |
| 2507 | |
| 2508 | let completed = wait_for_completed_shell(&mut manager, &task_id); |
| 2509 | assert_ne!(completed.status, ShellStatus::Running); |
| 2510 | let owned = manager |
| 2511 | .list_jobs_for_session("session-a") |
| 2512 | .into_iter() |
| 2513 | .find(|job| job.id == task_id) |
| 2514 | .expect("A job remains visible to A"); |
| 2515 | assert_eq!(owned.owner_session_id, "session-a"); |
| 2516 | assert!( |
| 2517 | manager |
| 2518 | .drain_finished_jobs_with_evidence_for_session("session-b") |
| 2519 | .is_empty(), |
| 2520 | "B must not claim A's completion" |
| 2521 | ); |
| 2522 | assert!(manager.has_finished_unreported_jobs_for_session("session-a")); |
| 2523 | let first = manager.drain_finished_jobs_with_evidence_for_session("session-a"); |
| 2524 | assert_eq!(first.len(), 1); |
| 2525 | assert_eq!(first[0].event.owner_session_id, "session-a"); |
| 2526 | assert!(first[0].event.stdout_tail.contains("owned-by-a")); |
| 2527 | assert!( |
| 2528 | manager |
| 2529 | .drain_finished_jobs_with_evidence_for_session("session-a") |
| 2530 | .is_empty(), |
| 2531 | "A completion is delivered exactly once" |
| 2532 | ); |
| 2533 | } |
| 2534 | |
| 2535 | #[test] |
| 2536 | fn completion_evidence_preserves_arbitrary_stream_bytes() { |
| 2537 | use base64::Engine as _; |
| 2538 | |
| 2539 | let stdout = vec![b'o', 0, 0xff, b'k']; |
| 2540 | let stderr = vec![0xfe, b'e', b'r', b'r']; |
| 2541 | let evidence = ShellCompletionEvidence { |
| 2542 | event: ShellCompletionEvent { |
| 2543 | task_id: "shell_binary".to_string(), |
| 2544 | command: "binary-output".to_string(), |
| 2545 | status: ShellStatus::Completed, |
| 2546 | started_at: None, |
| 2547 | cause: Some(ShellTerminationCause::Producer), |
| 2548 | producer_reported: true, |
| 2549 | exit_code: Some(0), |
| 2550 | duration_ms: 17, |
| 2551 | stdout_tail: String::new(), |
| 2552 | stderr_tail: String::new(), |
| 2553 | stdout_len: stdout.len(), |
| 2554 | stderr_len: stderr.len(), |
| 2555 | evidence_ref: None, |
| 2556 | linked_task_id: None, |
| 2557 | owner_agent_id: None, |
| 2558 | owner_agent_name: None, |
| 2559 | origin_tool_call_id: Some("tool-origin".to_string()), |
| 2560 | origin_turn_id: Some("turn-origin".to_string()), |
| 2561 | owner_session_id: "session-test".to_string(), |
| 2562 | }, |
| 2563 | stdout: stdout.clone(), |
| 2564 | stderr: stderr.clone(), |
| 2565 | stdout_omitted: 0, |
| 2566 | stderr_omitted: 0, |
| 2567 | persisted_artifact: None, |
| 2568 | }; |
| 2569 | |
| 2570 | let payload: serde_json::Value = |
| 2571 | serde_json::from_slice(&evidence.artifact_bytes()).expect("evidence JSON"); |
| 2572 | assert_eq!(payload["stdout"]["encoding"], "base64"); |
| 2573 | assert_eq!(payload["stderr"]["encoding"], "base64"); |
| 2574 | assert_eq!(payload["origin_tool_call_id"], "tool-origin"); |
| 2575 | assert_eq!(payload["origin_turn_id"], "turn-origin"); |
| 2576 | let decoded_stdout = base64::engine::general_purpose::STANDARD |
| 2577 | .decode(payload["stdout"]["content"].as_str().expect("stdout data")) |
| 2578 | .expect("decode stdout"); |
| 2579 | let decoded_stderr = base64::engine::general_purpose::STANDARD |
| 2580 | .decode(payload["stderr"]["content"].as_str().expect("stderr data")) |
| 2581 | .expect("decode stderr"); |
| 2582 | assert_eq!(decoded_stdout, stdout); |
| 2583 | assert_eq!(decoded_stderr, stderr); |
| 2584 | } |
| 2585 | |
| 2586 | #[test] |
| 2587 | #[cfg(unix)] |
| 2588 | fn shell_execution_scrubs_parent_env_and_keeps_explicit_env() { |
| 2589 | let _lock = crate::test_support::lock_test_env(); |
| 2590 | let _secret = |
| 2591 | crate::test_support::EnvVarGuard::set("DEEPSEEK_CHILD_ENV_SHELL_SECRET", "parent-secret"); |
| 2592 | |
| 2593 | let tmp = tempdir().expect("tempdir"); |
| 2594 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2595 | let mut extra = std::collections::HashMap::new(); |
| 2596 | extra.insert( |
| 2597 | "DEEPSEEK_CHILD_ENV_EXPLICIT".to_string(), |
| 2598 | "explicit-value".to_string(), |
| 2599 | ); |
| 2600 | |
| 2601 | let result = manager |
| 2602 | .execute_with_options_env( |
| 2603 | "sh -c 'printf \"%s\\n%s\\n\" \"${DEEPSEEK_CHILD_ENV_SHELL_SECRET-unset}\" \"${DEEPSEEK_CHILD_ENV_EXPLICIT-unset}\"'", |
| 2604 | None, |
| 2605 | 5000, |
| 2606 | false, |
| 2607 | None, |
| 2608 | false, |
| 2609 | None, |
| 2610 | extra, |
| 2611 | ) |
| 2612 | .expect("execute"); |
| 2613 | |
| 2614 | assert_eq!(result.status, ShellStatus::Completed); |
| 2615 | assert_eq!(result.stdout, "unset\nexplicit-value\n"); |
| 2616 | } |
| 2617 | |
| 2618 | #[test] |
| 2619 | #[cfg(windows)] |
| 2620 | fn shell_execution_preserves_custom_windows_sdk_root_env() { |
| 2621 | let _lock = crate::test_support::lock_test_env(); |
| 2622 | let _sdk = crate::test_support::EnvVarGuard::set("BIMRV_SDK_ROOT", r"F:\Lib\BimRv27.5"); |
| 2623 | let _secret = crate::test_support::EnvVarGuard::set("MY_SECRET_ROOT", r"F:\Secrets"); |
| 2624 | |
| 2625 | let tmp = tempdir().expect("tempdir"); |
| 2626 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2627 | let command = if codewhale_sandbox::shell_dispatcher::global_dispatcher() |
| 2628 | .kind() |
| 2629 | .is_powershell() |
| 2630 | { |
| 2631 | r#"[Console]::WriteLine($env:BIMRV_SDK_ROOT); if ($null -eq $env:MY_SECRET_ROOT) { [Console]::WriteLine("secret-unset") } else { [Console]::WriteLine("secret-set") }"# |
| 2632 | .to_string() |
| 2633 | } else { |
| 2634 | r#"echo %BIMRV_SDK_ROOT% & if defined MY_SECRET_ROOT (echo secret-set) else (echo secret-unset)"# |
| 2635 | .to_string() |
| 2636 | }; |
| 2637 | |
| 2638 | let result = execute_shell(&mut manager, &command, None, 5000, false).expect("execute"); |
| 2639 | |
| 2640 | assert_eq!(result.status, ShellStatus::Completed); |
| 2641 | assert!( |
| 2642 | result.stdout.contains(r"F:\Lib\BimRv27.5"), |
| 2643 | "custom SDK root should reach exec_shell stdout: {:?}", |
| 2644 | result |
| 2645 | ); |
| 2646 | assert!( |
| 2647 | result.stdout.contains("secret-unset"), |
| 2648 | "secret-like env should stay scrubbed: {:?}", |
| 2649 | result |
| 2650 | ); |
| 2651 | } |
| 2652 | |
| 2653 | #[test] |
| 2654 | fn test_sync_execution() { |
| 2655 | let tmp = tempdir().expect("tempdir"); |
| 2656 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2657 | |
| 2658 | let result = |
| 2659 | execute_shell(&mut manager, &echo_command("hello"), None, 5000, false).expect("execute"); |
| 2660 | |
| 2661 | assert_eq!(result.status, ShellStatus::Completed); |
| 2662 | assert!(result.stdout.contains("hello")); |
| 2663 | assert!(result.task_id.is_none()); |
| 2664 | } |
| 2665 | |
| 2666 | #[test] |
| 2667 | fn test_background_execution() { |
| 2668 | let tmp = tempdir().expect("tempdir"); |
| 2669 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2670 | |
| 2671 | let result = execute_shell( |
| 2672 | &mut manager, |
| 2673 | &sleep_then_echo_command(1, "done"), |
| 2674 | None, |
| 2675 | 5000, |
| 2676 | true, |
| 2677 | ) |
| 2678 | .expect("execute"); |
| 2679 | |
| 2680 | assert_eq!(result.status, ShellStatus::Running); |
| 2681 | assert!(result.task_id.is_some()); |
| 2682 | |
| 2683 | let task_id = result |
| 2684 | .task_id |
| 2685 | .expect("background execution should return task_id"); |
| 2686 | |
| 2687 | let final_result = wait_for_completed_shell(&mut manager, &task_id); |
| 2688 | |
| 2689 | assert_eq!(final_result.status, ShellStatus::Completed); |
| 2690 | assert!(final_result.stdout.contains("done")); |
| 2691 | assert_eq!(final_result.exit_code, Some(0)); |
| 2692 | assert_eq!( |
| 2693 | manager.kill(&task_id).unwrap().status, |
| 2694 | ShellStatus::Completed |
| 2695 | ); |
| 2696 | #[cfg(unix)] |
| 2697 | assert!(manager.processes[&task_id].parent_death_watch.is_none()); |
| 2698 | } |
| 2699 | |
| 2700 | #[test] |
| 2701 | fn test_timeout() { |
| 2702 | let tmp = tempdir().expect("tempdir"); |
| 2703 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2704 | |
| 2705 | let result = |
| 2706 | execute_shell(&mut manager, &sleep_command(10), None, 1000, false).expect("execute"); |
| 2707 | |
| 2708 | assert_eq!(result.status, ShellStatus::TimedOut); |
| 2709 | } |
| 2710 | |
| 2711 | #[test] |
| 2712 | fn test_kill() { |
| 2713 | let tmp = tempdir().expect("tempdir"); |
| 2714 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2715 | |
| 2716 | let result = |
| 2717 | execute_shell(&mut manager, &sleep_command(60), None, 5000, true).expect("execute"); |
| 2718 | |
| 2719 | let task_id = result |
| 2720 | .task_id |
| 2721 | .expect("background execution should return task_id"); |
| 2722 | |
| 2723 | // Kill it |
| 2724 | let killed = manager.kill(&task_id).expect("kill"); |
| 2725 | assert_eq!(killed.status, ShellStatus::Killed); |
| 2726 | assert_eq!(manager.kill(&task_id).unwrap().status, ShellStatus::Killed); |
| 2727 | #[cfg(unix)] |
| 2728 | assert!(manager.processes[&task_id].parent_death_watch.is_none()); |
| 2729 | } |
| 2730 | |
| 2731 | #[test] |
| 2732 | fn kill_all_owned_running_ends_every_running_job_once() { |
| 2733 | let tmp = tempdir().expect("tempdir"); |
| 2734 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2735 | |
| 2736 | let first = execute_shell(&mut manager, &sleep_command(60), None, 5000, true) |
| 2737 | .expect("first") |
| 2738 | .task_id |
| 2739 | .expect("first task id"); |
| 2740 | let second = execute_shell(&mut manager, &sleep_command(60), None, 5000, true) |
| 2741 | .expect("second") |
| 2742 | .task_id |
| 2743 | .expect("second task id"); |
| 2744 | |
| 2745 | assert_eq!(manager.kill_all_owned_running(), 2); |
| 2746 | for id in [&first, &second] { |
| 2747 | let job = manager.inspect_job(id).expect("inspect job"); |
| 2748 | assert_eq!(job.snapshot.status, ShellStatus::Killed); |
| 2749 | } |
| 2750 | // Finished jobs are not recounted, so a repeat call is a no-op. |
| 2751 | assert_eq!(manager.kill_all_owned_running(), 0); |
| 2752 | } |
| 2753 | |
| 2754 | #[test] |
| 2755 | fn test_write_stdin_streams_output() { |
| 2756 | let tmp = tempdir().expect("tempdir"); |
| 2757 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2758 | |
| 2759 | let result = manager |
| 2760 | .execute_with_options_env( |
| 2761 | &echo_stdin_command(), |
| 2762 | None, |
| 2763 | 5000, |
| 2764 | true, |
| 2765 | None, |
| 2766 | false, |
| 2767 | None, |
| 2768 | HashMap::new(), |
| 2769 | ) |
| 2770 | .expect("execute"); |
| 2771 | |
| 2772 | let task_id = result |
| 2773 | .task_id |
| 2774 | .expect("background execution should return task_id"); |
| 2775 | |
| 2776 | manager |
| 2777 | .write_stdin(&task_id, "hello\n", true) |
| 2778 | .expect("write stdin"); |
| 2779 | |
| 2780 | let delta = manager |
| 2781 | .get_output_delta(&task_id, true, 5000) |
| 2782 | .expect("get_output_delta"); |
| 2783 | |
| 2784 | assert!(delta.result.stdout.contains("hello")); |
| 2785 | |
| 2786 | let delta2 = manager |
| 2787 | .get_output_delta(&task_id, false, 0) |
| 2788 | .expect("get_output_delta"); |
| 2789 | assert!(delta2.result.stdout.is_empty()); |
| 2790 | } |
| 2791 | |
| 2792 | #[test] |
| 2793 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 2794 | fn background_tty_command_has_controlling_terminal() { |
| 2795 | let tmp = tempdir().expect("tempdir"); |
| 2796 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2797 | |
| 2798 | let result = manager |
| 2799 | .execute_with_options_env( |
| 2800 | "sh -c 'exec 3<>/dev/tty && printf tty-ok && exec 3>&-'", |
| 2801 | None, |
| 2802 | 5000, |
| 2803 | true, |
| 2804 | None, |
| 2805 | true, |
| 2806 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 2807 | HashMap::new(), |
| 2808 | ) |
| 2809 | .expect("execute tty command"); |
| 2810 | |
| 2811 | let task_id = result |
| 2812 | .task_id |
| 2813 | .expect("background tty execution should return task_id"); |
| 2814 | |
| 2815 | let done = manager |
| 2816 | .get_output(&task_id, true, 10_000) |
| 2817 | .expect("get tty command output"); |
| 2818 | |
| 2819 | assert_eq!(done.status, ShellStatus::Completed); |
| 2820 | assert_eq!(done.exit_code, Some(0)); |
| 2821 | assert!( |
| 2822 | done.stdout.contains("tty-ok"), |
| 2823 | "tty output should confirm /dev/tty opened; got {done:?}" |
| 2824 | ); |
| 2825 | } |
| 2826 | |
| 2827 | #[test] |
| 2828 | fn test_job_list_poll_cancel_and_stale_snapshot() { |
| 2829 | let tmp = tempdir().expect("tempdir"); |
| 2830 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2831 | |
| 2832 | let started = execute_shell( |
| 2833 | &mut manager, |
| 2834 | &sleep_then_echo_command(1, "done"), |
| 2835 | None, |
| 2836 | 5000, |
| 2837 | true, |
| 2838 | ) |
| 2839 | .expect("execute"); |
| 2840 | let task_id = started.task_id.expect("task id"); |
| 2841 | manager |
| 2842 | .tag_linked_task(&task_id, Some("task_123".to_string())) |
| 2843 | .expect("tag linked task"); |
| 2844 | |
| 2845 | let running = manager.list_jobs(); |
| 2846 | let job = running |
| 2847 | .iter() |
| 2848 | .find(|job| job.id == task_id) |
| 2849 | .expect("running job"); |
| 2850 | assert_eq!(job.status, ShellStatus::Running); |
| 2851 | assert_eq!(job.linked_task_id.as_deref(), Some("task_123")); |
| 2852 | assert!(job.command.contains("done")); |
| 2853 | assert_eq!(job.cwd, tmp.path()); |
| 2854 | |
| 2855 | let completed = manager |
| 2856 | .poll_delta(&task_id, true, 5000) |
| 2857 | .expect("poll delta"); |
| 2858 | assert_eq!(completed.result.status, ShellStatus::Completed); |
| 2859 | assert!(completed.result.stdout.contains("done")); |
| 2860 | |
| 2861 | let detail = manager.inspect_job(&task_id).expect("inspect"); |
| 2862 | assert!(detail.stdout.contains("done")); |
| 2863 | assert_eq!(detail.snapshot.status, ShellStatus::Completed); |
| 2864 | |
| 2865 | manager.remember_stale_job( |
| 2866 | "shell_stale", |
| 2867 | "cargo test", |
| 2868 | tmp.path().to_path_buf(), |
| 2869 | Some("task_old".to_string()), |
| 2870 | ); |
| 2871 | let stale = manager |
| 2872 | .list_jobs() |
| 2873 | .into_iter() |
| 2874 | .find(|job| job.id == "shell_stale") |
| 2875 | .expect("stale job"); |
| 2876 | assert!(stale.stale); |
| 2877 | assert_eq!(stale.linked_task_id.as_deref(), Some("task_old")); |
| 2878 | } |
| 2879 | |
| 2880 | #[test] |
| 2881 | fn running_job_snapshot_keeps_silent_live_job_live() { |
| 2882 | let tmp = tempdir().expect("tempdir"); |
| 2883 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2884 | |
| 2885 | let started = |
| 2886 | execute_shell(&mut manager, &sleep_command(5), None, 5000, true).expect("execute"); |
| 2887 | let task_id = started.task_id.expect("task id"); |
| 2888 | |
| 2889 | { |
| 2890 | let shell = manager.processes.get_mut(&task_id).expect("live shell"); |
| 2891 | shell.last_output_at = Instant::now() - QUIET_NO_OUTPUT_AFTER - Duration::from_millis(1); |
| 2892 | } |
| 2893 | |
| 2894 | let job = manager |
| 2895 | .list_jobs() |
| 2896 | .into_iter() |
| 2897 | .find(|job| job.id == task_id) |
| 2898 | .expect("running job"); |
| 2899 | |
| 2900 | assert_eq!(job.status, ShellStatus::Running); |
| 2901 | assert!(!job.stale, "silence alone must not mark a live job stale"); |
| 2902 | assert!( |
| 2903 | job.elapsed_since_output_ms |
| 2904 | .is_some_and(|elapsed| elapsed >= QUIET_NO_OUTPUT_AFTER.as_millis() as u64), |
| 2905 | "elapsed no-output time should be exposed: {job:?}" |
| 2906 | ); |
| 2907 | } |
| 2908 | |
| 2909 | #[test] |
| 2910 | fn running_job_snapshot_keeps_recent_no_output_fresh() { |
| 2911 | let tmp = tempdir().expect("tempdir"); |
| 2912 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2913 | |
| 2914 | let started = |
| 2915 | execute_shell(&mut manager, &sleep_command(5), None, 5000, true).expect("execute"); |
| 2916 | let task_id = started.task_id.expect("task id"); |
| 2917 | |
| 2918 | let job = manager |
| 2919 | .list_jobs() |
| 2920 | .into_iter() |
| 2921 | .find(|job| job.id == task_id) |
| 2922 | .expect("running job"); |
| 2923 | |
| 2924 | assert_eq!(job.status, ShellStatus::Running); |
| 2925 | assert!(!job.stale, "fresh running job should not start stale"); |
| 2926 | assert!(job.elapsed_since_output_ms.is_some()); |
| 2927 | } |
| 2928 | |
| 2929 | #[test] |
| 2930 | fn test_job_cancel_updates_completion_state() { |
| 2931 | let tmp = tempdir().expect("tempdir"); |
| 2932 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 2933 | |
| 2934 | let started = |
| 2935 | execute_shell(&mut manager, &sleep_command(60), None, 5000, true).expect("execute"); |
| 2936 | let task_id = started.task_id.expect("task id"); |
| 2937 | |
| 2938 | let killed = manager.kill(&task_id).expect("kill"); |
| 2939 | assert_eq!(killed.status, ShellStatus::Killed); |
| 2940 | let job = manager.inspect_job(&task_id).expect("inspect"); |
| 2941 | assert_eq!(job.snapshot.status, ShellStatus::Killed); |
| 2942 | assert!(!job.snapshot.stdin_available); |
| 2943 | } |
| 2944 | |
| 2945 | #[test] |
| 2946 | fn test_output_truncation() { |
| 2947 | let long_output = "x".repeat(50_000); |
| 2948 | let (truncated, _meta) = truncate_with_meta(&long_output); |
| 2949 | |
| 2950 | assert!(truncated.len() < long_output.len()); |
| 2951 | assert!(truncated.contains("truncated")); |
| 2952 | } |
| 2953 | |
| 2954 | #[test] |
| 2955 | fn test_truncate_with_meta_reports_omission_counts() { |
| 2956 | let long_output = format!("line1\nline2\n{}", "x".repeat(60_000)); |
| 2957 | let (truncated, meta) = truncate_with_meta(&long_output); |
| 2958 | |
| 2959 | assert!(meta.truncated); |
| 2960 | assert!(meta.original_len >= long_output.len()); |
| 2961 | assert!(meta.omitted > 0); |
| 2962 | assert!(truncated.contains("bytes omitted")); |
| 2963 | } |
| 2964 | |
| 2965 | #[test] |
| 2966 | fn network_restricted_hint_detects_silent_curl_failure() { |
| 2967 | let tmp = tempdir().expect("tempdir"); |
| 2968 | let ctx = network_restricted_context(tmp.path()); |
| 2969 | let result = failed_network_shell_result("000", ""); |
| 2970 | |
| 2971 | let hint = shell_network_restricted_hint( |
| 2972 | &ctx, |
| 2973 | "curl -s -o /dev/null -w '%{http_code}' https://api.github.com", |
| 2974 | &result, |
| 2975 | ) |
| 2976 | .expect("network-restricted hint"); |
| 2977 | |
| 2978 | assert!(hint.contains("Plan mode")); |
| 2979 | } |
| 2980 | |
| 2981 | #[test] |
| 2982 | fn sandbox_denied_hint_names_the_effective_posture() { |
| 2983 | // DGF-02: an approved write blocked by a read-only sandbox must come |
| 2984 | // back naming the sandbox as the blocker, never as a bare failure. |
| 2985 | let tmp = tempdir().expect("tempdir"); |
| 2986 | let ctx = ToolContext::new(tmp.path()) |
| 2987 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::read_only()); |
| 2988 | let mut result = |
| 2989 | failed_network_shell_result("", "sh: cannot create out.txt: Operation not permitted"); |
| 2990 | result.sandbox_denied = true; |
| 2991 | |
| 2992 | let hint = shell_sandbox_denied_hint(&ctx, &result).expect("sandbox-denied hint"); |
| 2993 | |
| 2994 | assert!(hint.contains("read-only"), "{hint}"); |
| 2995 | assert!(hint.contains("Ask-only escalation"), "{hint}"); |
| 2996 | assert!( |
| 2997 | hint.contains("retry this exact command once with sandbox_permissions"), |
| 2998 | "{hint}" |
| 2999 | ); |
| 3000 | assert!(hint.contains("justification"), "{hint}"); |
| 3001 | } |
| 3002 | |
| 3003 | #[test] |
| 3004 | fn contract_bash_denial_surfaces_the_escalation_shape() { |
| 3005 | let tmp = tempdir().expect("tempdir"); |
| 3006 | let ctx = ToolContext::new(tmp.path()) |
| 3007 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::read_only()); |
| 3008 | let mut result = failed_network_shell_result("", "Operation not permitted"); |
| 3009 | result.sandbox_denied = true; |
| 3010 | |
| 3011 | let error = finish_contract_bash_result( |
| 3012 | result, None, &ctx, None, false, None, None, false, None, None, |
| 3013 | ) |
| 3014 | .expect_err("sandbox denial is a failed call"); |
| 3015 | |
| 3016 | assert!( |
| 3017 | error |
| 3018 | .to_string() |
| 3019 | .contains("retry this exact command once with sandbox_permissions"), |
| 3020 | "{error}" |
| 3021 | ); |
| 3022 | } |
| 3023 | |
| 3024 | #[test] |
| 3025 | fn sandbox_denied_hint_absent_without_denial_or_policy() { |
| 3026 | let tmp = tempdir().expect("tempdir"); |
| 3027 | let ctx = ToolContext::new(tmp.path()) |
| 3028 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::read_only()); |
| 3029 | let undenied = failed_network_shell_result("", "No such file or directory"); |
| 3030 | assert!(shell_sandbox_denied_hint(&ctx, &undenied).is_none()); |
| 3031 | |
| 3032 | let mut denied = failed_network_shell_result("", ""); |
| 3033 | denied.sandbox_denied = true; |
| 3034 | let no_policy_ctx = ToolContext::new(tmp.path()); |
| 3035 | assert!(shell_sandbox_denied_hint(&no_policy_ctx, &denied).is_none()); |
| 3036 | } |
| 3037 | |
| 3038 | #[test] |
| 3039 | fn shell_delta_result_surfaces_sandbox_denied_hint() { |
| 3040 | let tmp = tempdir().expect("tempdir"); |
| 3041 | let ctx = ToolContext::new(tmp.path()) |
| 3042 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::read_only()); |
| 3043 | let mut result = failed_network_shell_result("", "Operation not permitted"); |
| 3044 | result.sandbox_denied = true; |
| 3045 | |
| 3046 | let tool_result = build_shell_delta_tool_result( |
| 3047 | ShellDeltaResult { |
| 3048 | command: "touch out.txt".to_string(), |
| 3049 | result, |
| 3050 | stdout_total_len: 0, |
| 3051 | stderr_total_len: 0, |
| 3052 | }, |
| 3053 | &ctx, |
| 3054 | ); |
| 3055 | |
| 3056 | assert!( |
| 3057 | tool_result |
| 3058 | .content |
| 3059 | .contains("The execution sandbox blocked this command"), |
| 3060 | "{}", |
| 3061 | tool_result.content |
| 3062 | ); |
| 3063 | let metadata = tool_result.metadata.expect("metadata"); |
| 3064 | assert!(metadata.get("sandbox_denied_hint").is_some()); |
| 3065 | } |
| 3066 | |
| 3067 | #[test] |
| 3068 | fn network_restricted_hint_ignores_local_failures() { |
| 3069 | let tmp = tempdir().expect("tempdir"); |
| 3070 | let ctx = network_restricted_context(tmp.path()); |
| 3071 | let result = failed_network_shell_result("", "No such file or directory"); |
| 3072 | |
| 3073 | assert!(shell_network_restricted_hint(&ctx, "cat missing.txt", &result).is_none()); |
| 3074 | } |
| 3075 | |
| 3076 | #[test] |
| 3077 | fn readonly_denied_hint_classifies_refusals_and_ignores_success_or_bwrap() { |
| 3078 | let tmp = tempdir().expect("tempdir"); |
| 3079 | let full_ctx = ToolContext::new(tmp.path()); |
| 3080 | let mut agent_ctx = ToolContext::new(tmp.path()); |
| 3081 | agent_ctx.shell_policy = ShellPolicy::ReadOnly; |
| 3082 | agent_ctx.owner_agent_id = Some("scout-1".to_string()); |
| 3083 | |
| 3084 | let ok_rg = ShellResult { |
| 3085 | task_id: None, |
| 3086 | status: ShellStatus::Completed, |
| 3087 | exit_code: Some(0), |
| 3088 | stdout: "fail with `Operation not permitted`".to_string(), |
| 3089 | stderr: String::new(), |
| 3090 | duration_ms: 1, |
| 3091 | stdout_len: 37, |
| 3092 | stderr_len: 0, |
| 3093 | stdout_omitted: 0, |
| 3094 | stderr_omitted: 0, |
| 3095 | stdout_truncated: false, |
| 3096 | stderr_truncated: false, |
| 3097 | sandboxed: true, |
| 3098 | sandbox_type: Some("seatbelt".to_string()), |
| 3099 | sandbox_denied: false, |
| 3100 | }; |
| 3101 | assert!( |
| 3102 | readonly_denied_hint_for_os(&full_ctx, "rg ps docs/SANDBOX.md", &ok_rg, true).is_none() |
| 3103 | ); |
| 3104 | |
| 3105 | let mut running = ok_rg.clone(); |
| 3106 | running.status = ShellStatus::Running; |
| 3107 | running.exit_code = None; |
| 3108 | assert!(readonly_denied_hint_for_os(&full_ctx, "mktemp", &running, true).is_none()); |
| 3109 | |
| 3110 | let mut bwrap_fail = failed_network_shell_result( |
| 3111 | "", |
| 3112 | "bwrap: Creating new namespace failed: Operation not permitted", |
| 3113 | ); |
| 3114 | bwrap_fail.sandbox_denied = true; |
| 3115 | assert!(readonly_denied_hint_for_os(&full_ctx, "ls", &bwrap_fail, false).is_none()); |
| 3116 | |
| 3117 | let ps_fail = failed_network_shell_result("", "/bin/sh: /bin/ps: Operation not permitted"); |
| 3118 | assert_eq!( |
| 3119 | readonly_denied_hint_for_os(&full_ctx, "sh -c 'ps'", &ps_fail, true), |
| 3120 | Some(READONLY_SETUID_DENIED_HINT) |
| 3121 | ); |
| 3122 | assert_eq!( |
| 3123 | readonly_denied_hint_for_os(&full_ctx, "ps aux", &ps_fail, false), |
| 3124 | Some(READONLY_WRITE_DENIED_HINT) |
| 3125 | ); |
| 3126 | |
| 3127 | let top_operand = failed_network_shell_result("", "zsh:1: operation not permitted: top"); |
| 3128 | assert_eq!( |
| 3129 | readonly_denied_hint_for_os(&full_ctx, "printf x > top", &top_operand, true), |
| 3130 | Some(READONLY_WRITE_DENIED_HINT) |
| 3131 | ); |
| 3132 | assert_eq!( |
| 3133 | readonly_denied_hint_for_os(&agent_ctx, "rm -rf crates/top", &top_operand, true), |
| 3134 | Some(READONLY_AGENT_WRITE_DENIED_HINT) |
| 3135 | ); |
| 3136 | |
| 3137 | let mktemp_fail = failed_network_shell_result( |
| 3138 | "", |
| 3139 | "mktemp: mkstemp failed on /var/folders/xx/T/tmp.123: Operation not permitted", |
| 3140 | ); |
| 3141 | assert_eq!( |
| 3142 | readonly_denied_hint_for_os(&full_ctx, "mktemp", &mktemp_fail, true), |
| 3143 | Some(READONLY_MACOS_MKTEMP_HINT) |
| 3144 | ); |
| 3145 | assert!(!READONLY_MACOS_MKTEMP_HINT.contains("heredocs")); |
| 3146 | |
| 3147 | let heredoc_fail = failed_network_shell_result( |
| 3148 | "", |
| 3149 | "/bin/sh: cannot create temp file for here document: Operation not permitted", |
| 3150 | ); |
| 3151 | assert_eq!( |
| 3152 | readonly_denied_hint_for_os(&full_ctx, "/bin/sh -c 'cat <<EOF'", &heredoc_fail, true), |
| 3153 | Some(READONLY_MACOS_HEREDOC_HINT) |
| 3154 | ); |
| 3155 | |
| 3156 | let mut gh_offline = failed_network_shell_result( |
| 3157 | "", |
| 3158 | "- The token in keyring is invalid.\nerror connecting to api.github.com", |
| 3159 | ); |
| 3160 | gh_offline.sandbox_denied = false; |
| 3161 | assert_eq!( |
| 3162 | readonly_offline_network_hint("gh auth status", &gh_offline), |
| 3163 | Some(READONLY_OFFLINE_NETWORK_HINT) |
| 3164 | ); |
| 3165 | |
| 3166 | let mut git_fetch_ro = failed_network_shell_result( |
| 3167 | "", |
| 3168 | "error: cannot open '.git/FETCH_HEAD': Read-only file system", |
| 3169 | ); |
| 3170 | git_fetch_ro.sandbox_denied = true; |
| 3171 | assert!(readonly_offline_network_hint("git fetch origin", &git_fetch_ro).is_none()); |
| 3172 | assert_eq!( |
| 3173 | readonly_denied_hint_for_os(&full_ctx, "git fetch origin", &git_fetch_ro, false), |
| 3174 | Some(READONLY_WRITE_DENIED_HINT) |
| 3175 | ); |
| 3176 | |
| 3177 | let err = finish_contract_bash_result( |
| 3178 | git_fetch_ro, |
| 3179 | None, |
| 3180 | &full_ctx, |
| 3181 | None, |
| 3182 | true, |
| 3183 | None, |
| 3184 | Some(READONLY_WRITE_DENIED_HINT), |
| 3185 | false, |
| 3186 | None, |
| 3187 | None, |
| 3188 | ) |
| 3189 | .expect_err("denied write fails"); |
| 3190 | let metadata = err.metadata().expect("metadata"); |
| 3191 | assert_eq!(metadata["sandbox_network"], true); |
| 3192 | assert!(metadata.get("sandbox_network_restricted").is_none()); |
| 3193 | assert_eq!(metadata["sandbox_denied_hint"], READONLY_WRITE_DENIED_HINT); |
| 3194 | } |
| 3195 | |
| 3196 | #[test] |
| 3197 | fn shell_delta_result_surfaces_network_restricted_hint() { |
| 3198 | let tmp = tempdir().expect("tempdir"); |
| 3199 | let ctx = network_restricted_context(tmp.path()); |
| 3200 | let result = failed_network_shell_result("000", ""); |
| 3201 | |
| 3202 | let tool_result = build_shell_delta_tool_result( |
| 3203 | ShellDeltaResult { |
| 3204 | command: "gh issue list".to_string(), |
| 3205 | result, |
| 3206 | stdout_total_len: 3, |
| 3207 | stderr_total_len: 0, |
| 3208 | }, |
| 3209 | &ctx, |
| 3210 | ); |
| 3211 | |
| 3212 | assert!(!tool_result.success); |
| 3213 | assert!(tool_result.content.starts_with("Shell command blocked")); |
| 3214 | let metadata = tool_result.metadata.expect("metadata"); |
| 3215 | assert_eq!( |
| 3216 | metadata |
| 3217 | .get("sandbox_network_restricted") |
| 3218 | .and_then(Value::as_bool), |
| 3219 | Some(true) |
| 3220 | ); |
| 3221 | } |
| 3222 | |
| 3223 | #[test] |
| 3224 | fn shell_delta_result_exposes_lossless_high_exit_code_and_hex() { |
| 3225 | let tmp = tempdir().expect("tempdir"); |
| 3226 | let ctx = ToolContext::new(tmp.path()); |
| 3227 | let mut result = failed_network_shell_result("", ""); |
| 3228 | result.exit_code = Some(0xC000_0005); |
| 3229 | |
| 3230 | let tool_result = build_shell_delta_tool_result( |
| 3231 | ShellDeltaResult { |
| 3232 | command: "echo probe".to_string(), |
| 3233 | result, |
| 3234 | stdout_total_len: 0, |
| 3235 | stderr_total_len: 0, |
| 3236 | }, |
| 3237 | &ctx, |
| 3238 | ); |
| 3239 | |
| 3240 | assert!( |
| 3241 | tool_result |
| 3242 | .content |
| 3243 | .contains("exit code 3221225477 (0xC0000005)"), |
| 3244 | "{}", |
| 3245 | tool_result.content |
| 3246 | ); |
| 3247 | let metadata = tool_result.metadata.expect("metadata"); |
| 3248 | assert_eq!(metadata["exit_code"], json!(3221225477_i64)); |
| 3249 | assert_eq!(metadata["exit_code_hex"], json!("0xC0000005")); |
| 3250 | } |
| 3251 | |
| 3252 | #[test] |
| 3253 | fn shell_delta_result_surfaces_elapsed_time_in_content() { |
| 3254 | let tmp = tempdir().expect("tempdir"); |
| 3255 | let ctx = ToolContext::new(tmp.path()); |
| 3256 | let mut result = failed_network_shell_result("", ""); |
| 3257 | result.status = ShellStatus::Running; |
| 3258 | result.duration_ms = 42_500; |
| 3259 | result.task_id = Some("shell-7".to_string()); |
| 3260 | |
| 3261 | let tool_result = build_shell_delta_tool_result( |
| 3262 | ShellDeltaResult { |
| 3263 | command: "cargo test --workspace".to_string(), |
| 3264 | result, |
| 3265 | stdout_total_len: 0, |
| 3266 | stderr_total_len: 0, |
| 3267 | }, |
| 3268 | &ctx, |
| 3269 | ); |
| 3270 | |
| 3271 | assert!( |
| 3272 | tool_result |
| 3273 | .content |
| 3274 | .starts_with("Task shell-7 still running after 42.5 s."), |
| 3275 | "{}", |
| 3276 | tool_result.content |
| 3277 | ); |
| 3278 | } |
| 3279 | |
| 3280 | #[test] |
| 3281 | fn shell_delta_timing_line_omits_task_id_when_unknown() { |
| 3282 | let tmp = tempdir().expect("tempdir"); |
| 3283 | let ctx = ToolContext::new(tmp.path()); |
| 3284 | // failed_network_shell_result: ShellStatus::Failed, duration_ms: 25, task_id: None. |
| 3285 | let result = failed_network_shell_result("", ""); |
| 3286 | |
| 3287 | let tool_result = build_shell_delta_tool_result( |
| 3288 | ShellDeltaResult { |
| 3289 | command: "echo probe".to_string(), |
| 3290 | result, |
| 3291 | stdout_total_len: 0, |
| 3292 | stderr_total_len: 0, |
| 3293 | }, |
| 3294 | &ctx, |
| 3295 | ); |
| 3296 | |
| 3297 | assert!( |
| 3298 | tool_result.content.starts_with("Task failed after 25 ms."), |
| 3299 | "{}", |
| 3300 | tool_result.content |
| 3301 | ); |
| 3302 | } |
| 3303 | |
| 3304 | #[test] |
| 3305 | fn shell_delta_timing_line_phrases_cover_terminal_statuses() { |
| 3306 | let tmp = tempdir().expect("tempdir"); |
| 3307 | let ctx = ToolContext::new(tmp.path()); |
| 3308 | for (status, phrase) in [ |
| 3309 | (ShellStatus::Completed, "completed"), |
| 3310 | (ShellStatus::Killed, "killed"), |
| 3311 | (ShellStatus::TimedOut, "timed out"), |
| 3312 | ] { |
| 3313 | let mut result = failed_network_shell_result("", ""); |
| 3314 | result.status = status; |
| 3315 | result.duration_ms = 5_000; |
| 3316 | let tool_result = build_shell_delta_tool_result( |
| 3317 | ShellDeltaResult { |
| 3318 | command: "echo probe".to_string(), |
| 3319 | result, |
| 3320 | stdout_total_len: 0, |
| 3321 | stderr_total_len: 0, |
| 3322 | }, |
| 3323 | &ctx, |
| 3324 | ); |
| 3325 | assert!( |
| 3326 | tool_result |
| 3327 | .content |
| 3328 | .starts_with(&format!("Task {phrase} after 5 s.")), |
| 3329 | "{}", |
| 3330 | tool_result.content |
| 3331 | ); |
| 3332 | } |
| 3333 | } |
| 3334 | |
| 3335 | #[test] |
| 3336 | fn shell_delta_timing_line_handles_zero_duration() { |
| 3337 | let tmp = tempdir().expect("tempdir"); |
| 3338 | let ctx = ToolContext::new(tmp.path()); |
| 3339 | let mut result = failed_network_shell_result("", ""); |
| 3340 | result.status = ShellStatus::Completed; |
| 3341 | result.duration_ms = 0; |
| 3342 | let tool_result = build_shell_delta_tool_result( |
| 3343 | ShellDeltaResult { |
| 3344 | command: "echo probe".to_string(), |
| 3345 | result, |
| 3346 | stdout_total_len: 0, |
| 3347 | stderr_total_len: 0, |
| 3348 | }, |
| 3349 | &ctx, |
| 3350 | ); |
| 3351 | assert!( |
| 3352 | tool_result |
| 3353 | .content |
| 3354 | .starts_with("Task completed after 0 ms."), |
| 3355 | "{}", |
| 3356 | tool_result.content |
| 3357 | ); |
| 3358 | } |
| 3359 | |
| 3360 | #[test] |
| 3361 | fn shell_delta_timing_line_sits_below_network_hint() { |
| 3362 | let tmp = tempdir().expect("tempdir"); |
| 3363 | let ctx = network_restricted_context(tmp.path()); |
| 3364 | let result = failed_network_shell_result("000", ""); |
| 3365 | let tool_result = build_shell_delta_tool_result( |
| 3366 | ShellDeltaResult { |
| 3367 | command: "gh issue list".to_string(), |
| 3368 | result, |
| 3369 | stdout_total_len: 3, |
| 3370 | stderr_total_len: 0, |
| 3371 | }, |
| 3372 | &ctx, |
| 3373 | ); |
| 3374 | let content = tool_result.content; |
| 3375 | let hint_pos = content.find("Shell command blocked").expect("hint present"); |
| 3376 | let timing_pos = content |
| 3377 | .find("failed after 25 ms") |
| 3378 | .expect("timing line present"); |
| 3379 | assert!( |
| 3380 | hint_pos < timing_pos, |
| 3381 | "hint must precede timing line: {content}" |
| 3382 | ); |
| 3383 | } |
| 3384 | |
| 3385 | #[test] |
| 3386 | fn shell_delta_result_includes_cargo_failure_summary() { |
| 3387 | let tmp = tempdir().expect("tempdir"); |
| 3388 | let ctx = ToolContext::new(tmp.path()); |
| 3389 | let result = ShellResult { |
| 3390 | task_id: None, |
| 3391 | status: ShellStatus::Failed, |
| 3392 | exit_code: Some(101), |
| 3393 | stdout: "running 1 test\ntest tests::fails ... FAILED\n\nfailures:\n\n---- tests::fails stdout ----\nthread 'tests::fails' panicked at src/lib.rs:7:9:\nboom\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; finished in 0.00s\n".to_string(), |
| 3394 | stderr: "error: test failed, to rerun pass `--lib`".to_string(), |
| 3395 | duration_ms: 12, |
| 3396 | stdout_len: 0, |
| 3397 | stderr_len: 0, |
| 3398 | stdout_omitted: 0, |
| 3399 | stderr_omitted: 0, |
| 3400 | stdout_truncated: false, |
| 3401 | stderr_truncated: false, |
| 3402 | sandboxed: false, |
| 3403 | sandbox_type: None, |
| 3404 | sandbox_denied: false, |
| 3405 | }; |
| 3406 | |
| 3407 | let tool_result = build_shell_delta_tool_result( |
| 3408 | ShellDeltaResult { |
| 3409 | command: "cargo test".to_string(), |
| 3410 | result, |
| 3411 | stdout_total_len: 0, |
| 3412 | stderr_total_len: 0, |
| 3413 | }, |
| 3414 | &ctx, |
| 3415 | ); |
| 3416 | |
| 3417 | let metadata = tool_result.metadata.expect("metadata"); |
| 3418 | assert_eq!( |
| 3419 | metadata["cargo_failure_summary"]["kind"], |
| 3420 | json!("test_failure") |
| 3421 | ); |
| 3422 | assert!( |
| 3423 | metadata["cargo_failure_summary"]["summary"] |
| 3424 | .as_str() |
| 3425 | .unwrap() |
| 3426 | .contains("Failing tests: tests::fails") |
| 3427 | ); |
| 3428 | assert!( |
| 3429 | metadata["summary"] |
| 3430 | .as_str() |
| 3431 | .unwrap() |
| 3432 | .contains("error: test failed") |
| 3433 | ); |
| 3434 | } |
| 3435 | |
| 3436 | #[test] |
| 3437 | fn shell_delta_result_keeps_existing_summary_for_generic_cargo_failure() { |
| 3438 | let tmp = tempdir().expect("tempdir"); |
| 3439 | let ctx = ToolContext::new(tmp.path()); |
| 3440 | let result = ShellResult { |
| 3441 | task_id: None, |
| 3442 | status: ShellStatus::Failed, |
| 3443 | exit_code: Some(1), |
| 3444 | stdout: "build failed".to_string(), |
| 3445 | stderr: "command failed without structured cargo diagnostics".to_string(), |
| 3446 | duration_ms: 12, |
| 3447 | stdout_len: 0, |
| 3448 | stderr_len: 0, |
| 3449 | stdout_omitted: 0, |
| 3450 | stderr_omitted: 0, |
| 3451 | stdout_truncated: false, |
| 3452 | stderr_truncated: false, |
| 3453 | sandboxed: false, |
| 3454 | sandbox_type: None, |
| 3455 | sandbox_denied: false, |
| 3456 | }; |
| 3457 | |
| 3458 | let tool_result = build_shell_delta_tool_result( |
| 3459 | ShellDeltaResult { |
| 3460 | command: "cargo test".to_string(), |
| 3461 | result, |
| 3462 | stdout_total_len: 0, |
| 3463 | stderr_total_len: 0, |
| 3464 | }, |
| 3465 | &ctx, |
| 3466 | ); |
| 3467 | |
| 3468 | let metadata = tool_result.metadata.expect("metadata"); |
| 3469 | assert!(metadata.get("cargo_failure_summary").is_none()); |
| 3470 | assert_eq!( |
| 3471 | metadata["summary"], |
| 3472 | json!("command failed without structured cargo diagnostics") |
| 3473 | ); |
| 3474 | } |
| 3475 | |
| 3476 | #[test] |
| 3477 | fn shell_delta_result_surfaces_python_build_dependency_hint() { |
| 3478 | let tmp = tempdir().expect("tempdir"); |
| 3479 | let ctx = ToolContext::new(tmp.path()); |
| 3480 | let result = ShellResult { |
| 3481 | task_id: None, |
| 3482 | status: ShellStatus::Failed, |
| 3483 | exit_code: Some(1), |
| 3484 | stdout: String::new(), |
| 3485 | stderr: "running build_ext\nModuleNotFoundError: No module named 'setuptools'\n" |
| 3486 | .to_string(), |
| 3487 | duration_ms: 12, |
| 3488 | stdout_len: 0, |
| 3489 | stderr_len: 72, |
| 3490 | stdout_omitted: 0, |
| 3491 | stderr_omitted: 0, |
| 3492 | stdout_truncated: false, |
| 3493 | stderr_truncated: false, |
| 3494 | sandboxed: false, |
| 3495 | sandbox_type: None, |
| 3496 | sandbox_denied: false, |
| 3497 | }; |
| 3498 | |
| 3499 | let tool_result = build_shell_delta_tool_result( |
| 3500 | ShellDeltaResult { |
| 3501 | command: "python setup.py build_ext --inplace".to_string(), |
| 3502 | result, |
| 3503 | stdout_total_len: 0, |
| 3504 | stderr_total_len: 72, |
| 3505 | }, |
| 3506 | &ctx, |
| 3507 | ); |
| 3508 | |
| 3509 | assert!(!tool_result.success); |
| 3510 | assert!( |
| 3511 | tool_result |
| 3512 | .content |
| 3513 | .starts_with("Python build dependency missing") |
| 3514 | ); |
| 3515 | let metadata = tool_result.metadata.expect("metadata"); |
| 3516 | assert_eq!( |
| 3517 | metadata["python_build_dependency_hint"]["kind"], |
| 3518 | json!("missing_setuptools") |
| 3519 | ); |
| 3520 | assert!( |
| 3521 | metadata["python_build_dependency_hint"]["hint"] |
| 3522 | .as_str() |
| 3523 | .unwrap() |
| 3524 | .contains("setuptools") |
| 3525 | ); |
| 3526 | } |
| 3527 | |
| 3528 | #[test] |
| 3529 | fn test_summarize_output_strips_truncation_note() { |
| 3530 | let long_output = "x".repeat(60_000); |
| 3531 | let (truncated, _meta) = truncate_with_meta(&long_output); |
| 3532 | let summary = summarize_output(&truncated); |
| 3533 | assert!(!summary.contains("Output truncated at")); |
| 3534 | } |
| 3535 | |
| 3536 | #[tokio::test] |
| 3537 | async fn test_exec_shell_metadata_includes_summaries() { |
| 3538 | let tmp = tempdir().expect("tempdir"); |
| 3539 | let ctx = ToolContext::new(tmp.path()); |
| 3540 | let tool = BashTool::new("Bash"); |
| 3541 | |
| 3542 | let result = tool |
| 3543 | .execute(json!({"command": echo_command("hello")}), &ctx) |
| 3544 | .await |
| 3545 | .expect("execute"); |
| 3546 | assert!(result.success); |
| 3547 | |
| 3548 | let meta = result.metadata.expect("metadata"); |
| 3549 | let summary = meta |
| 3550 | .get("summary") |
| 3551 | .and_then(Value::as_str) |
| 3552 | .unwrap_or_default() |
| 3553 | .to_string(); |
| 3554 | assert!(summary.contains("hello")); |
| 3555 | assert!(meta.get("stdout_len").is_some()); |
| 3556 | assert!(meta.get("stdout_truncated").is_some()); |
| 3557 | } |
| 3558 | |
| 3559 | #[cfg(not(windows))] |
| 3560 | #[tokio::test] |
| 3561 | async fn test_exec_shell_combined_output_uses_single_stream() { |
| 3562 | let tmp = tempdir().expect("tempdir"); |
| 3563 | let ctx = ToolContext::new(tmp.path()); |
| 3564 | let tool = BashTool::new("Bash"); |
| 3565 | let command = "printf 'out\\n'; printf 'err\\n' >&2"; |
| 3566 | |
| 3567 | let result = tool |
| 3568 | .execute(json!({"command": command, "combined_output": true}), &ctx) |
| 3569 | .await |
| 3570 | .expect("execute"); |
| 3571 | assert!(result.success, "{}", result.content); |
| 3572 | assert!(result.content.contains("out"), "{}", result.content); |
| 3573 | assert!(result.content.contains("err"), "{}", result.content); |
| 3574 | |
| 3575 | let meta = result.metadata.expect("metadata"); |
| 3576 | assert_eq!( |
| 3577 | meta.get("combined_output").and_then(Value::as_bool), |
| 3578 | Some(true) |
| 3579 | ); |
| 3580 | } |
| 3581 | |
| 3582 | #[test] |
| 3583 | fn background_schema_distinguishes_temporary_jobs_from_persistent_services() { |
| 3584 | let schema = BashTool::new("Bash").input_schema(); |
| 3585 | let d = schema["properties"]["background"]["description"] |
| 3586 | .as_str() |
| 3587 | .expect("background description"); |
| 3588 | assert!(d.contains("killed") && d.contains("background:true") && d.contains("persist:true")); |
| 3589 | } |
| 3590 | |
| 3591 | #[tokio::test] |
| 3592 | async fn test_exec_shell_foreground_cancel_kills_process() { |
| 3593 | let tmp = tempdir().expect("tempdir"); |
| 3594 | let cancel_token = tokio_util::sync::CancellationToken::new(); |
| 3595 | let ctx = ToolContext::new(tmp.path()).with_cancel_token(cancel_token.clone()); |
| 3596 | let command = sleep_command(30); |
| 3597 | |
| 3598 | let task = tokio::spawn(async move { |
| 3599 | BashTool::new("Bash") |
| 3600 | .execute( |
| 3601 | json!({ |
| 3602 | "command": command, |
| 3603 | "timeout_ms": 600_000 |
| 3604 | }), |
| 3605 | &ctx, |
| 3606 | ) |
| 3607 | .await |
| 3608 | .expect("execute") |
| 3609 | }); |
| 3610 | |
| 3611 | tokio::time::sleep(Duration::from_millis(150)).await; |
| 3612 | cancel_token.cancel(); |
| 3613 | |
| 3614 | let result = tokio::time::timeout(Duration::from_secs(5), task) |
| 3615 | .await |
| 3616 | .expect("foreground shell should observe cancellation") |
| 3617 | .expect("task should not panic"); |
| 3618 | |
| 3619 | assert!(!result.success); |
| 3620 | assert!(result.content.contains("Command canceled")); |
| 3621 | let meta = result.metadata.expect("metadata"); |
| 3622 | assert_eq!(meta.get("status").and_then(Value::as_str), Some("Killed")); |
| 3623 | assert_eq!(meta.get("canceled").and_then(Value::as_bool), Some(true)); |
| 3624 | } |
| 3625 | |
| 3626 | #[tokio::test] |
| 3627 | async fn test_exec_shell_foreground_can_move_to_background() { |
| 3628 | let tmp = tempdir().expect("tempdir"); |
| 3629 | let ctx = ToolContext::new(tmp.path()); |
| 3630 | let shell_manager = ctx.shell_manager.clone(); |
| 3631 | let command = sleep_command(30); |
| 3632 | let task_ctx = ctx.clone(); |
| 3633 | |
| 3634 | let task = tokio::spawn(async move { |
| 3635 | BashTool::new("Bash") |
| 3636 | .execute( |
| 3637 | json!({ |
| 3638 | "command": command, |
| 3639 | "timeout_ms": 600_000 |
| 3640 | }), |
| 3641 | &task_ctx, |
| 3642 | ) |
| 3643 | .await |
| 3644 | .expect("execute") |
| 3645 | }); |
| 3646 | |
| 3647 | await_shell_wait_registration(&ctx).await; |
| 3648 | shell_manager |
| 3649 | .lock() |
| 3650 | .expect("shell manager lock") |
| 3651 | .request_shell_wait_detach("workspace"); |
| 3652 | |
| 3653 | let result = tokio::time::timeout(Duration::from_secs(5), task) |
| 3654 | .await |
| 3655 | .expect("foreground shell should detach") |
| 3656 | .expect("task should not panic"); |
| 3657 | |
| 3658 | assert!(result.success); |
| 3659 | assert!(result.content.contains("moved to the background")); |
| 3660 | // The detach message points the model at a tool it can actually call. |
| 3661 | // `Bash` is hidden; `task_shell_wait` is eager, so the message names it directly. |
| 3662 | assert!( |
| 3663 | result.content.contains("`task_shell_wait` directly"), |
| 3664 | "{}", |
| 3665 | result.content |
| 3666 | ); |
| 3667 | assert!(result.content.contains("task_id="), "{}", result.content); |
| 3668 | assert!(result.content.contains("cancel=true"), "{}", result.content); |
| 3669 | assert!(!result.content.contains("exec_shell"), "{}", result.content); |
| 3670 | |
| 3671 | let meta = result.metadata.expect("metadata"); |
| 3672 | assert_eq!(meta.get("status").and_then(Value::as_str), Some("Running")); |
| 3673 | assert_eq!( |
| 3674 | meta.get("backgrounded").and_then(Value::as_bool), |
| 3675 | Some(true) |
| 3676 | ); |
| 3677 | let task_id = meta |
| 3678 | .get("task_id") |
| 3679 | .and_then(Value::as_str) |
| 3680 | .expect("task id") |
| 3681 | .to_string(); |
| 3682 | |
| 3683 | let mut manager = shell_manager.lock().expect("shell manager lock"); |
| 3684 | let job = manager.inspect_job(&task_id).expect("inspect job"); |
| 3685 | assert_eq!(job.snapshot.status, ShellStatus::Running); |
| 3686 | assert!( |
| 3687 | job.snapshot.background, |
| 3688 | "detached foreground work needs a background receipt" |
| 3689 | ); |
| 3690 | let killed = manager.kill(&task_id).expect("kill"); |
| 3691 | assert_eq!(killed.status, ShellStatus::Killed); |
| 3692 | } |
| 3693 | |
| 3694 | #[cfg(unix)] |
| 3695 | #[tokio::test] |
| 3696 | async fn dropped_foreground_wait_kills_descendants_and_retains_unreceived_output() { |
| 3697 | let tmp = tempdir().unwrap(); |
| 3698 | let pid_file = tmp.path().join("descendant.pid"); |
| 3699 | let command = format!( |
| 3700 | "printf 'retained-before-drop\\n'; printf '%{}s\\n' x; \ |
| 3701 | CODEWHALE_SHELL_DESCENDANT_HELPER=1 \ |
| 3702 | CODEWHALE_SHELL_DESCENDANT_PID_FILE={} {} --exact \ |
| 3703 | tools::shell::tests::shell_descendant_helper_process --nocapture", |
| 3704 | RAW_STREAM_SETTLED_TAIL_BYTES + 1024, |
| 3705 | shell_words::quote(&pid_file.display().to_string()), |
| 3706 | shell_words::quote(&std::env::current_exe().unwrap().display().to_string()), |
| 3707 | ); |
| 3708 | let ctx = ToolContext::new(tmp.path()).with_state_namespace("foreground-drop".to_string()); |
| 3709 | let manager = ctx.shell_manager.clone(); |
| 3710 | let task_ctx = ctx.clone(); |
| 3711 | let task = tokio::spawn(async move { |
| 3712 | BashTool::new("Bash") |
| 3713 | .execute( |
| 3714 | json!({"command": command, "timeout_ms": 600_000}), |
| 3715 | &task_ctx, |
| 3716 | ) |
| 3717 | .await |
| 3718 | }); |
| 3719 | let descendant = tokio::time::timeout(Duration::from_secs(10), async { |
| 3720 | loop { |
| 3721 | if let Ok(raw) = std::fs::read_to_string(&pid_file) |
| 3722 | && let Ok(pid) = raw.trim().parse::<libc::pid_t>() |
| 3723 | { |
| 3724 | break pid; |
| 3725 | } |
| 3726 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 3727 | } |
| 3728 | }) |
| 3729 | .await |
| 3730 | .expect("descendant must start"); |
| 3731 | task.abort(); |
| 3732 | assert!(task.await.unwrap_err().is_cancelled()); |
| 3733 | assert!( |
| 3734 | wait_for_shell_pid_exit(descendant), |
| 3735 | "dropping the wait must stop its descendant" |
| 3736 | ); |
| 3737 | let mut manager = manager.lock().unwrap(); |
| 3738 | let jobs = manager.list_jobs_for_session("foreground-drop"); |
| 3739 | assert_eq!(jobs.len(), 1); |
| 3740 | assert_eq!(jobs[0].status, ShellStatus::Killed); |
| 3741 | let detail = manager |
| 3742 | .inspect_job(&jobs[0].id) |
| 3743 | .expect("inspect cancelled job"); |
| 3744 | assert!(detail.stdout.contains("retained-before-drop")); |
| 3745 | assert!(detail.stdout.len() > RAW_STREAM_SETTLED_TAIL_BYTES); |
| 3746 | assert!(!manager.has_finished_unreported_jobs_for_session("foreground-drop")); |
| 3747 | } |
| 3748 | |
| 3749 | #[tokio::test] |
| 3750 | async fn lowercase_bash_foreground_detach_is_a_successful_running_receipt() { |
| 3751 | let tmp = tempdir().expect("tempdir"); |
| 3752 | let ctx = ToolContext::new(tmp.path()); |
| 3753 | let shell_manager = ctx.shell_manager.clone(); |
| 3754 | let command = sleep_command(30); |
| 3755 | let task_ctx = ctx.clone(); |
| 3756 | |
| 3757 | let task = tokio::spawn(async move { |
| 3758 | LowercaseBashTool |
| 3759 | .execute(json!({"command": command}), &task_ctx) |
| 3760 | .await |
| 3761 | .expect("execute") |
| 3762 | }); |
| 3763 | |
| 3764 | await_shell_wait_registration(&ctx).await; |
| 3765 | shell_manager |
| 3766 | .lock() |
| 3767 | .expect("shell manager lock") |
| 3768 | .request_shell_wait_detach("workspace"); |
| 3769 | |
| 3770 | let result = tokio::time::timeout(Duration::from_secs(5), task) |
| 3771 | .await |
| 3772 | .expect("foreground shell should detach") |
| 3773 | .expect("task should not panic"); |
| 3774 | |
| 3775 | assert!(result.success, "{}", result.content); |
| 3776 | assert!( |
| 3777 | result.content.contains("moved to the background") |
| 3778 | && result.content.contains("not killed") |
| 3779 | && result.content.contains("`task_shell_wait` directly"), |
| 3780 | "{}", |
| 3781 | result.content |
| 3782 | ); |
| 3783 | // A model that owns a stuck command learns here how to stop it; no other |
| 3784 | // tool in its catalog can. |
| 3785 | assert!(result.content.contains("cancel=true"), "{}", result.content); |
| 3786 | assert!(!result.content.contains("code -1"), "{}", result.content); |
| 3787 | let metadata = result.metadata.expect("metadata"); |
| 3788 | assert_eq!(metadata["status"], "Running"); |
| 3789 | assert_eq!(metadata["backgrounded"], true); |
| 3790 | let task_id = metadata["task_id"].as_str().expect("task id"); |
| 3791 | |
| 3792 | let mut manager = shell_manager.lock().expect("shell manager lock"); |
| 3793 | let job = manager.inspect_job(task_id).expect("inspect job"); |
| 3794 | assert_eq!(job.snapshot.status, ShellStatus::Running); |
| 3795 | manager.kill(task_id).expect("kill test job"); |
| 3796 | } |
| 3797 | |
| 3798 | async fn start_wait_detach_job(context: &ToolContext, command: String) -> String { |
| 3799 | BashTool::new("Bash") |
| 3800 | .execute(json!({"command": command, "background": true}), context) |
| 3801 | .await |
| 3802 | .expect("start owned background job") |
| 3803 | .metadata |
| 3804 | .unwrap()["task_id"] |
| 3805 | .as_str() |
| 3806 | .unwrap() |
| 3807 | .to_string() |
| 3808 | } |
| 3809 | |
| 3810 | async fn await_shell_wait_registration(context: &ToolContext) { |
| 3811 | tokio::time::timeout(Duration::from_secs(3), async { |
| 3812 | loop { |
| 3813 | if context |
| 3814 | .shell_manager |
| 3815 | .lock() |
| 3816 | .unwrap() |
| 3817 | .shell_wait_active_for_test(&context.state_namespace) |
| 3818 | { |
| 3819 | break; |
| 3820 | } |
| 3821 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 3822 | } |
| 3823 | }) |
| 3824 | .await |
| 3825 | .expect("blocking shell wait registered"); |
| 3826 | } |
| 3827 | |
| 3828 | fn wait_detach_output_command(marker: &str) -> String { |
| 3829 | let separator = if cfg!(windows) |
| 3830 | && !codewhale_sandbox::shell_dispatcher::global_dispatcher() |
| 3831 | .kind() |
| 3832 | .is_powershell() |
| 3833 | { |
| 3834 | "&" |
| 3835 | } else { |
| 3836 | ";" |
| 3837 | }; |
| 3838 | format!("{} {separator} {}", echo_command(marker), sleep_command(30)) |
| 3839 | } |
| 3840 | |
| 3841 | async fn await_wait_detach_output(context: &ToolContext, id: &str, marker: &str) { |
| 3842 | tokio::time::timeout(Duration::from_secs(3), async { |
| 3843 | loop { |
| 3844 | if context |
| 3845 | .shell_manager |
| 3846 | .lock() |
| 3847 | .unwrap() |
| 3848 | .inspect_job(id) |
| 3849 | .unwrap() |
| 3850 | .stdout |
| 3851 | .contains(marker) |
| 3852 | { |
| 3853 | break; |
| 3854 | } |
| 3855 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 3856 | } |
| 3857 | }) |
| 3858 | .await |
| 3859 | .expect("job produced output before wait"); |
| 3860 | } |
| 3861 | |
| 3862 | #[tokio::test] |
| 3863 | async fn background_wait_detaches_promptly_preserves_output_and_owned_process() { |
| 3864 | let tmp = tempdir().unwrap(); |
| 3865 | let context = ToolContext::new(tmp.path()).with_state_namespace("detach-owner"); |
| 3866 | let id = |
| 3867 | start_wait_detach_job(&context, wait_detach_output_command("detach-output-canary")).await; |
| 3868 | await_wait_detach_output(&context, &id, "detach-output-canary").await; |
| 3869 | let wait_context = context.clone(); |
| 3870 | let wait_id = id.clone(); |
| 3871 | let mut waiting = tokio::spawn(async move { |
| 3872 | BashTool::alias("exec_shell_wait", "wait") |
| 3873 | .execute( |
| 3874 | json!({"task_id": wait_id, "timeout_ms": 600_000}), |
| 3875 | &wait_context, |
| 3876 | ) |
| 3877 | .await |
| 3878 | }); |
| 3879 | await_shell_wait_registration(&context).await; |
| 3880 | assert!( |
| 3881 | !context |
| 3882 | .shell_manager |
| 3883 | .lock() |
| 3884 | .unwrap() |
| 3885 | .request_shell_wait_detach("other-session") |
| 3886 | ); |
| 3887 | assert!(!waiting.is_finished()); |
| 3888 | assert!( |
| 3889 | context |
| 3890 | .shell_manager |
| 3891 | .lock() |
| 3892 | .unwrap() |
| 3893 | .request_shell_wait_detach(&context.state_namespace) |
| 3894 | ); |
| 3895 | let returned = tokio::time::timeout(Duration::from_secs(3), &mut waiting).await; |
| 3896 | if returned.is_err() { |
| 3897 | waiting.abort(); |
| 3898 | context |
| 3899 | .shell_manager |
| 3900 | .lock() |
| 3901 | .unwrap() |
| 3902 | .kill_for_session(&context.state_namespace, &id) |
| 3903 | .unwrap(); |
| 3904 | } |
| 3905 | let result = returned |
| 3906 | .expect("detach must release a ten-minute wait promptly") |
| 3907 | .unwrap() |
| 3908 | .unwrap(); |
| 3909 | let alive = context |
| 3910 | .shell_manager |
| 3911 | .lock() |
| 3912 | .unwrap() |
| 3913 | .inspect_job_for_session(&context.state_namespace, &id) |
| 3914 | .unwrap() |
| 3915 | .snapshot |
| 3916 | .status; |
| 3917 | let next = BashTool::alias("exec_shell_wait", "wait") |
| 3918 | .execute(json!({"task_id": id, "wait": false}), &context) |
| 3919 | .await |
| 3920 | .unwrap(); |
| 3921 | context |
| 3922 | .shell_manager |
| 3923 | .lock() |
| 3924 | .unwrap() |
| 3925 | .kill_for_session(&context.state_namespace, &id) |
| 3926 | .unwrap(); |
| 3927 | assert!(result.success); |
| 3928 | assert_eq!(result.metadata.as_ref().unwrap()["status"], "Running"); |
| 3929 | assert_eq!(result.metadata.as_ref().unwrap()["wait_detached"], true); |
| 3930 | assert!( |
| 3931 | result |
| 3932 | .metadata |
| 3933 | .as_ref() |
| 3934 | .unwrap() |
| 3935 | .get("wait_canceled") |
| 3936 | .is_none() |
| 3937 | ); |
| 3938 | assert_eq!(alive, ShellStatus::Running); |
| 3939 | assert_eq!(result.content.matches("detach-output-canary").count(), 1); |
| 3940 | assert!( |
| 3941 | !next.content.contains("detach-output-canary"), |
| 3942 | "detach consumes each output byte once" |
| 3943 | ); |
| 3944 | assert!( |
| 3945 | !context |
| 3946 | .shell_manager |
| 3947 | .lock() |
| 3948 | .unwrap() |
| 3949 | .request_shell_wait_detach(&context.state_namespace) |
| 3950 | ); |
| 3951 | } |
| 3952 | |
| 3953 | #[tokio::test] |
| 3954 | async fn multi_background_wait_detach_is_session_scoped_and_rejects_foreign_jobs() { |
| 3955 | let tmp = tempdir().unwrap(); |
| 3956 | let owner = ToolContext::new(tmp.path()).with_state_namespace("multi-owner"); |
| 3957 | let foreign = owner.clone().with_state_namespace("multi-foreign"); |
| 3958 | let first = |
| 3959 | start_wait_detach_job(&owner, wait_detach_output_command("multi-output-canary")).await; |
| 3960 | await_wait_detach_output(&owner, &first, "multi-output-canary").await; |
| 3961 | let second = start_wait_detach_job(&owner, sleep_command(30)).await; |
| 3962 | let other = start_wait_detach_job(&foreign, sleep_command(30)).await; |
| 3963 | let rejected = BashTool::alias("exec_shell_wait", "wait") |
| 3964 | .execute( |
| 3965 | json!({"task_ids": [first, other], "timeout_ms": 600_000}), |
| 3966 | &owner, |
| 3967 | ) |
| 3968 | .await; |
| 3969 | assert!( |
| 3970 | rejected.is_err(), |
| 3971 | "every job must belong to the waiting session" |
| 3972 | ); |
| 3973 | assert!( |
| 3974 | !owner |
| 3975 | .shell_manager |
| 3976 | .lock() |
| 3977 | .unwrap() |
| 3978 | .shell_wait_active_for_test(&owner.state_namespace) |
| 3979 | ); |
| 3980 | let wait_context = owner.clone(); |
| 3981 | let ids = vec![first.clone(), second.clone()]; |
| 3982 | let mut waiting = tokio::spawn(async move { |
| 3983 | BashTool::alias("exec_shell_wait", "wait") |
| 3984 | .execute( |
| 3985 | json!({"task_ids": ids, "until": "all", "timeout_ms": 600_000}), |
| 3986 | &wait_context, |
| 3987 | ) |
| 3988 | .await |
| 3989 | }); |
| 3990 | let foreign_context = foreign.clone(); |
| 3991 | let other_id = other.clone(); |
| 3992 | let mut foreign_wait = tokio::spawn(async move { |
| 3993 | BashTool::alias("exec_shell_wait", "wait") |
| 3994 | .execute( |
| 3995 | json!({"task_id": other_id, "timeout_ms": 600_000}), |
| 3996 | &foreign_context, |
| 3997 | ) |
| 3998 | .await |
| 3999 | }); |
| 4000 | await_shell_wait_registration(&owner).await; |
| 4001 | await_shell_wait_registration(&foreign).await; |
| 4002 | assert!( |
| 4003 | owner |
| 4004 | .shell_manager |
| 4005 | .lock() |
| 4006 | .unwrap() |
| 4007 | .request_shell_wait_detach(&owner.state_namespace) |
| 4008 | ); |
| 4009 | let returned = tokio::time::timeout(Duration::from_secs(3), &mut waiting).await; |
| 4010 | let foreign_still_waiting = !foreign_wait.is_finished(); |
| 4011 | assert!( |
| 4012 | owner |
| 4013 | .shell_manager |
| 4014 | .lock() |
| 4015 | .unwrap() |
| 4016 | .request_shell_wait_detach(&foreign.state_namespace) |
| 4017 | ); |
| 4018 | let foreign_returned = tokio::time::timeout(Duration::from_secs(3), &mut foreign_wait).await; |
| 4019 | waiting.abort(); |
| 4020 | foreign_wait.abort(); |
| 4021 | let first_output = BashTool::alias("exec_shell_wait", "wait") |
| 4022 | .execute(json!({"task_id": first, "wait": false}), &owner) |
| 4023 | .await |
| 4024 | .unwrap(); |
| 4025 | let next_output = BashTool::alias("exec_shell_wait", "wait") |
| 4026 | .execute(json!({"task_id": first, "wait": false}), &owner) |
| 4027 | .await |
| 4028 | .unwrap(); |
| 4029 | let mut manager = owner.shell_manager.lock().unwrap(); |
| 4030 | let statuses: Vec<_> = [&first, &second, &other] |
| 4031 | .into_iter() |
| 4032 | .map(|id| manager.inspect_job(id).unwrap().snapshot.status) |
| 4033 | .collect(); |
| 4034 | manager |
| 4035 | .kill_for_session(&owner.state_namespace, &first) |
| 4036 | .unwrap(); |
| 4037 | manager |
| 4038 | .kill_for_session(&owner.state_namespace, &second) |
| 4039 | .unwrap(); |
| 4040 | manager |
| 4041 | .kill_for_session(&foreign.state_namespace, &other) |
| 4042 | .unwrap(); |
| 4043 | drop(manager); |
| 4044 | let result = returned |
| 4045 | .expect("multi-wait must detach promptly") |
| 4046 | .unwrap() |
| 4047 | .unwrap(); |
| 4048 | assert!(result.success); |
| 4049 | assert_eq!(result.metadata.as_ref().unwrap()["wait_detached"], true); |
| 4050 | assert_eq!( |
| 4051 | result.metadata.as_ref().unwrap()["statuses"][&first], |
| 4052 | "Running" |
| 4053 | ); |
| 4054 | assert_eq!( |
| 4055 | result.metadata.as_ref().unwrap()["statuses"][&second], |
| 4056 | "Running" |
| 4057 | ); |
| 4058 | assert!(foreign_still_waiting, "detaching A must not release B"); |
| 4059 | let foreign_result = foreign_returned |
| 4060 | .expect("foreign session can release its own wait") |
| 4061 | .unwrap() |
| 4062 | .unwrap(); |
| 4063 | assert_eq!( |
| 4064 | foreign_result.metadata.as_ref().unwrap()["wait_detached"], |
| 4065 | true |
| 4066 | ); |
| 4067 | assert_eq!( |
| 4068 | first_output.content.matches("multi-output-canary").count(), |
| 4069 | 1 |
| 4070 | ); |
| 4071 | assert!( |
| 4072 | !next_output.content.contains("multi-output-canary"), |
| 4073 | "multi-wait must not consume output cursors" |
| 4074 | ); |
| 4075 | assert!( |
| 4076 | statuses |
| 4077 | .into_iter() |
| 4078 | .all(|status| status == ShellStatus::Running) |
| 4079 | ); |
| 4080 | assert!( |
| 4081 | !owner |
| 4082 | .shell_manager |
| 4083 | .lock() |
| 4084 | .unwrap() |
| 4085 | .request_shell_wait_detach(&owner.state_namespace) |
| 4086 | ); |
| 4087 | } |
| 4088 | |
| 4089 | #[tokio::test] |
| 4090 | async fn shell_wait_detach_expires_and_turn_cancellation_keeps_precedence() { |
| 4091 | let tmp = tempdir().unwrap(); |
| 4092 | let cancel = tokio_util::sync::CancellationToken::new(); |
| 4093 | let context = ToolContext::new(tmp.path()) |
| 4094 | .with_state_namespace("cancel-owner") |
| 4095 | .with_cancel_token(cancel.clone()); |
| 4096 | let id = start_wait_detach_job(&context, sleep_command(30)).await; |
| 4097 | { |
| 4098 | let mut manager = context.shell_manager.lock().unwrap(); |
| 4099 | let previous = manager.register_shell_wait(&context.state_namespace); |
| 4100 | assert!(manager.request_shell_wait_detach(&context.state_namespace)); |
| 4101 | drop(previous); |
| 4102 | assert!(!manager.request_shell_wait_detach(&context.state_namespace)); |
| 4103 | } |
| 4104 | // An old request must not free a fresh wait. Dropping its future must also |
| 4105 | // unregister it, so a later request cannot affect the next call. |
| 4106 | assert!( |
| 4107 | tokio::time::timeout( |
| 4108 | Duration::from_millis(100), |
| 4109 | BashTool::alias("exec_shell_wait", "wait") |
| 4110 | .execute(json!({"task_id": id, "timeout_ms": 600_000}), &context) |
| 4111 | ) |
| 4112 | .await |
| 4113 | .is_err() |
| 4114 | ); |
| 4115 | assert!( |
| 4116 | !context |
| 4117 | .shell_manager |
| 4118 | .lock() |
| 4119 | .unwrap() |
| 4120 | .request_shell_wait_detach(&context.state_namespace) |
| 4121 | ); |
| 4122 | let wait_context = context.clone(); |
| 4123 | let wait_id = id.clone(); |
| 4124 | let mut waiting = tokio::spawn(async move { |
| 4125 | BashTool::alias("exec_shell_wait", "wait") |
| 4126 | .execute( |
| 4127 | json!({"task_id": wait_id, "timeout_ms": 600_000}), |
| 4128 | &wait_context, |
| 4129 | ) |
| 4130 | .await |
| 4131 | }); |
| 4132 | await_shell_wait_registration(&context).await; |
| 4133 | context |
| 4134 | .shell_manager |
| 4135 | .lock() |
| 4136 | .unwrap() |
| 4137 | .request_shell_wait_detach(&context.state_namespace); |
| 4138 | cancel.cancel(); |
| 4139 | let returned = tokio::time::timeout(Duration::from_secs(3), &mut waiting).await; |
| 4140 | waiting.abort(); |
| 4141 | let alive = context |
| 4142 | .shell_manager |
| 4143 | .lock() |
| 4144 | .unwrap() |
| 4145 | .inspect_job(&id) |
| 4146 | .unwrap() |
| 4147 | .snapshot |
| 4148 | .status; |
| 4149 | context |
| 4150 | .shell_manager |
| 4151 | .lock() |
| 4152 | .unwrap() |
| 4153 | .kill_for_session(&context.state_namespace, &id) |
| 4154 | .unwrap(); |
| 4155 | let result = returned |
| 4156 | .expect("cancel releases wait promptly") |
| 4157 | .unwrap() |
| 4158 | .unwrap(); |
| 4159 | assert_eq!(result.metadata.as_ref().unwrap()["wait_canceled"], true); |
| 4160 | assert!( |
| 4161 | result |
| 4162 | .metadata |
| 4163 | .as_ref() |
| 4164 | .unwrap() |
| 4165 | .get("wait_detached") |
| 4166 | .is_none() |
| 4167 | ); |
| 4168 | assert_eq!(alive, ShellStatus::Running); |
| 4169 | } |
| 4170 | |
| 4171 | #[tokio::test] |
| 4172 | async fn test_exec_shell_wait_cancel_leaves_background_process_running() { |
| 4173 | let tmp = tempdir().expect("tempdir"); |
| 4174 | let cancel_token = tokio_util::sync::CancellationToken::new(); |
| 4175 | let ctx = ToolContext::new(tmp.path()).with_cancel_token(cancel_token.clone()); |
| 4176 | let shell_manager = ctx.shell_manager.clone(); |
| 4177 | let started = execute_shell( |
| 4178 | &mut shell_manager.lock().expect("shell manager lock"), |
| 4179 | &sleep_command(30), |
| 4180 | None, |
| 4181 | 600_000, |
| 4182 | true, |
| 4183 | ) |
| 4184 | .expect("execute"); |
| 4185 | let task_id = started.task_id.expect("task id"); |
| 4186 | let wait_task_id = task_id.clone(); |
| 4187 | let task_ctx = ctx.clone(); |
| 4188 | |
| 4189 | let task = tokio::spawn(async move { |
| 4190 | BashTool::new("Bash") |
| 4191 | .execute( |
| 4192 | json!({ |
| 4193 | "action": "wait", |
| 4194 | "task_id": wait_task_id, |
| 4195 | "timeout_ms": 600_000 |
| 4196 | }), |
| 4197 | &task_ctx, |
| 4198 | ) |
| 4199 | .await |
| 4200 | .expect("wait") |
| 4201 | }); |
| 4202 | |
| 4203 | tokio::time::sleep(Duration::from_millis(150)).await; |
| 4204 | cancel_token.cancel(); |
| 4205 | |
| 4206 | let result = tokio::time::timeout(Duration::from_secs(5), task) |
| 4207 | .await |
| 4208 | .expect("wait should observe cancellation") |
| 4209 | .expect("task should not panic"); |
| 4210 | |
| 4211 | assert!(result.success); |
| 4212 | assert!(result.content.contains("still running")); |
| 4213 | let meta = result.metadata.expect("metadata"); |
| 4214 | assert_eq!(meta.get("status").and_then(Value::as_str), Some("Running")); |
| 4215 | assert_eq!( |
| 4216 | meta.get("wait_canceled").and_then(Value::as_bool), |
| 4217 | Some(true) |
| 4218 | ); |
| 4219 | |
| 4220 | let mut manager = shell_manager.lock().expect("shell manager lock"); |
| 4221 | let job = manager.inspect_job(&task_id).expect("inspect job"); |
| 4222 | assert_eq!(job.snapshot.status, ShellStatus::Running); |
| 4223 | let killed = manager.kill(&task_id).expect("kill"); |
| 4224 | assert_eq!(killed.status, ShellStatus::Killed); |
| 4225 | } |
| 4226 | |
| 4227 | #[tokio::test] |
| 4228 | async fn test_completed_background_shell_releases_process_handles() { |
| 4229 | let tmp = tempdir().expect("tempdir"); |
| 4230 | let ctx = ToolContext::new(tmp.path()); |
| 4231 | let shell_manager = ctx.shell_manager.clone(); |
| 4232 | let started = execute_shell( |
| 4233 | &mut shell_manager.lock().expect("shell manager lock"), |
| 4234 | &echo_command("done"), |
| 4235 | None, |
| 4236 | 600_000, |
| 4237 | true, |
| 4238 | ) |
| 4239 | .expect("execute"); |
| 4240 | let task_id = started.task_id.expect("task id"); |
| 4241 | |
| 4242 | let result = BashTool::alias("exec_shell_wait", "wait") |
| 4243 | .execute( |
| 4244 | json!({ |
| 4245 | "task_id": task_id.clone(), |
| 4246 | "wait": true, |
| 4247 | "timeout_ms": BACKGROUND_COMPLETION_WAIT_MS |
| 4248 | }), |
| 4249 | &ctx, |
| 4250 | ) |
| 4251 | .await |
| 4252 | .expect("wait"); |
| 4253 | |
| 4254 | assert!(result.success); |
| 4255 | let mut manager = shell_manager.lock().expect("shell manager lock"); |
| 4256 | let result = wait_for_completed_shell(&mut manager, &task_id); |
| 4257 | assert_eq!(result.status, ShellStatus::Completed); |
| 4258 | let shell = manager.processes.get_mut(&task_id).expect("tracked shell"); |
| 4259 | shell.poll(); |
| 4260 | assert_eq!(shell.status, ShellStatus::Completed); |
| 4261 | assert!(shell.stdin.is_none()); |
| 4262 | assert!(shell.child.is_none()); |
| 4263 | assert!(shell.stdout_thread.is_none()); |
| 4264 | assert!(shell.stderr_thread.is_none()); |
| 4265 | } |
| 4266 | |
| 4267 | #[cfg(unix)] |
| 4268 | #[tokio::test] |
| 4269 | async fn exec_shell_cancel_kills_descendant_process_group() { |
| 4270 | let tmp = tempdir().expect("tempdir"); |
| 4271 | let pid_file = tmp.path().join("descendant.pid"); |
| 4272 | let test_binary = std::env::current_exe().expect("current test binary"); |
| 4273 | let command = format!( |
| 4274 | "{} --exact {} --nocapture", |
| 4275 | shell_words::quote(&test_binary.display().to_string()), |
| 4276 | shell_words::quote("tools::shell::tests::shell_descendant_helper_process"), |
| 4277 | ); |
| 4278 | let ctx = ToolContext::new(tmp.path()); |
| 4279 | let mut env = std::collections::HashMap::new(); |
| 4280 | env.insert(SHELL_DESCENDANT_HELPER_ENV.to_string(), "1".to_string()); |
| 4281 | env.insert( |
| 4282 | SHELL_DESCENDANT_PID_FILE_ENV.to_string(), |
| 4283 | pid_file.display().to_string(), |
| 4284 | ); |
| 4285 | let started = ctx |
| 4286 | .shell_manager |
| 4287 | .lock() |
| 4288 | .expect("shell manager") |
| 4289 | .execute_with_options_env_for_session( |
| 4290 | &command, |
| 4291 | None, |
| 4292 | 60_000, |
| 4293 | true, |
| 4294 | None, |
| 4295 | false, |
| 4296 | None, |
| 4297 | env, |
| 4298 | &ctx.state_namespace, |
| 4299 | ) |
| 4300 | .expect("start descendant tree"); |
| 4301 | let task_id = started.task_id.expect("task id"); |
| 4302 | let descendant = wait_for_shell_pid_file(&pid_file); |
| 4303 | |
| 4304 | let result = BashTool::alias("exec_shell_cancel", "cancel") |
| 4305 | .execute(json!({"task_id": task_id}), &ctx) |
| 4306 | .await |
| 4307 | .expect("cancel process group"); |
| 4308 | assert!(result.success); |
| 4309 | assert!( |
| 4310 | wait_for_shell_pid_exit(descendant), |
| 4311 | "descendant {descendant} survived shell process-group cancellation" |
| 4312 | ); |
| 4313 | } |
| 4314 | |
| 4315 | #[tokio::test] |
| 4316 | async fn test_exec_shell_cancel_tool_kills_background_process() { |
| 4317 | let tmp = tempdir().expect("tempdir"); |
| 4318 | let ctx = ToolContext::new(tmp.path()); |
| 4319 | let shell_manager = ctx.shell_manager.clone(); |
| 4320 | let started = execute_shell( |
| 4321 | &mut shell_manager.lock().expect("shell manager lock"), |
| 4322 | &sleep_command(30), |
| 4323 | None, |
| 4324 | 600_000, |
| 4325 | true, |
| 4326 | ) |
| 4327 | .expect("execute"); |
| 4328 | let task_id = started.task_id.expect("task id"); |
| 4329 | |
| 4330 | let result = BashTool::alias("exec_shell_cancel", "cancel") |
| 4331 | .execute(json!({ "task_id": task_id }), &ctx) |
| 4332 | .await |
| 4333 | .expect("cancel"); |
| 4334 | |
| 4335 | assert!(result.success); |
| 4336 | assert!(result.content.contains("Canceled background command")); |
| 4337 | let meta = result.metadata.expect("metadata"); |
| 4338 | assert_eq!(meta.get("status").and_then(Value::as_str), Some("Killed")); |
| 4339 | |
| 4340 | let task_id = meta |
| 4341 | .get("task_id") |
| 4342 | .and_then(Value::as_str) |
| 4343 | .expect("task id"); |
| 4344 | let mut manager = shell_manager.lock().expect("shell manager lock"); |
| 4345 | let job = manager.inspect_job(task_id).expect("inspect job"); |
| 4346 | assert_eq!(job.snapshot.status, ShellStatus::Killed); |
| 4347 | } |
| 4348 | |
| 4349 | #[tokio::test] |
| 4350 | async fn test_exec_shell_cancel_tool_can_kill_all_running_processes() { |
| 4351 | let tmp = tempdir().expect("tempdir"); |
| 4352 | let ctx = ToolContext::new(tmp.path()); |
| 4353 | let shell_manager = ctx.shell_manager.clone(); |
| 4354 | let first = execute_shell( |
| 4355 | &mut shell_manager.lock().expect("shell manager lock"), |
| 4356 | &sleep_command(30), |
| 4357 | None, |
| 4358 | 600_000, |
| 4359 | true, |
| 4360 | ) |
| 4361 | .expect("execute first") |
| 4362 | .task_id |
| 4363 | .expect("first task id"); |
| 4364 | let second = execute_shell( |
| 4365 | &mut shell_manager.lock().expect("shell manager lock"), |
| 4366 | &sleep_command(30), |
| 4367 | None, |
| 4368 | 600_000, |
| 4369 | true, |
| 4370 | ) |
| 4371 | .expect("execute second") |
| 4372 | .task_id |
| 4373 | .expect("second task id"); |
| 4374 | |
| 4375 | let result = BashTool::alias("exec_shell_cancel", "cancel") |
| 4376 | .execute(json!({ "all": true }), &ctx) |
| 4377 | .await |
| 4378 | .expect("cancel all"); |
| 4379 | |
| 4380 | assert!(result.success); |
| 4381 | let meta = result.metadata.expect("metadata"); |
| 4382 | assert_eq!(meta.get("status").and_then(Value::as_str), Some("Killed")); |
| 4383 | assert_eq!(meta.get("canceled").and_then(Value::as_u64), Some(2)); |
| 4384 | |
| 4385 | let mut manager = shell_manager.lock().expect("shell manager lock"); |
| 4386 | let first_job = manager.inspect_job(&first).expect("inspect first"); |
| 4387 | let second_job = manager.inspect_job(&second).expect("inspect second"); |
| 4388 | assert_eq!(first_job.snapshot.status, ShellStatus::Killed); |
| 4389 | assert_eq!(second_job.snapshot.status, ShellStatus::Killed); |
| 4390 | } |
| 4391 | |
| 4392 | fn make_failed_result(stderr: &str) -> ShellResult { |
| 4393 | ShellResult { |
| 4394 | task_id: None, |
| 4395 | status: ShellStatus::Failed, |
| 4396 | exit_code: Some(1), |
| 4397 | stdout: String::new(), |
| 4398 | stderr: stderr.to_string(), |
| 4399 | duration_ms: 0, |
| 4400 | stdout_len: 0, |
| 4401 | stderr_len: stderr.len(), |
| 4402 | stdout_omitted: 0, |
| 4403 | stderr_omitted: 0, |
| 4404 | stdout_truncated: false, |
| 4405 | sandboxed: false, |
| 4406 | sandbox_type: None, |
| 4407 | sandbox_denied: false, |
| 4408 | stderr_truncated: false, |
| 4409 | } |
| 4410 | } |
| 4411 | |
| 4412 | #[test] |
| 4413 | fn test_macos_provenance_detected_by_activity_time_message() { |
| 4414 | let result = make_failed_result( |
| 4415 | "failed to update builder last activity time: open \ |
| 4416 | /Users/user/.docker/buildx/activity/.tmp-abc: operation not permitted", |
| 4417 | ); |
| 4418 | assert!(looks_like_macos_provenance_failure(&result)); |
| 4419 | } |
| 4420 | |
| 4421 | #[test] |
| 4422 | fn test_macos_provenance_detected_by_activity_path_and_eperm() { |
| 4423 | let result = make_failed_result( |
| 4424 | "error: open /home/user/.docker/buildx/activity/foo: operation not permitted", |
| 4425 | ); |
| 4426 | assert!(looks_like_macos_provenance_failure(&result)); |
| 4427 | } |
| 4428 | |
| 4429 | #[test] |
| 4430 | fn test_macos_provenance_not_triggered_on_success() { |
| 4431 | let mut result = make_failed_result( |
| 4432 | "failed to update builder last activity time: open \ |
| 4433 | /Users/user/.docker/buildx/activity/.tmp-abc: operation not permitted", |
| 4434 | ); |
| 4435 | result.status = ShellStatus::Completed; |
| 4436 | result.exit_code = Some(0); |
| 4437 | assert!(!looks_like_macos_provenance_failure(&result)); |
| 4438 | } |
| 4439 | |
| 4440 | #[test] |
| 4441 | fn test_macos_provenance_not_triggered_on_unrelated_eperm() { |
| 4442 | let result = make_failed_result("open /some/other/path: operation not permitted"); |
| 4443 | assert!(!looks_like_macos_provenance_failure(&result)); |
| 4444 | } |
| 4445 | |
| 4446 | // Regression test for #828: shell spawns an orphaned background subprocess |
| 4447 | // (simulating `nohup curl`) that keeps the pipe write-end open after the shell |
| 4448 | // exits. The readers must see EOF when the manager finishes the process group. |
| 4449 | #[cfg(unix)] |
| 4450 | #[test] |
| 4451 | fn test_orphaned_subprocess_does_not_block_collect_output() { |
| 4452 | let tmp = tempdir().expect("tempdir"); |
| 4453 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4454 | |
| 4455 | // sh spawns `sleep 100 &` and exits; the sleep subprocess inherits the |
| 4456 | // pipe write-ends and would keep reader threads blocked without the fix. |
| 4457 | let result = |
| 4458 | execute_shell(&mut manager, "sh -c 'sleep 100 &'", None, 5000, true).expect("execute"); |
| 4459 | let task_id = result.task_id.expect("task id"); |
| 4460 | |
| 4461 | // Drive to completion with a tight timeout — must not hang. |
| 4462 | let done = manager |
| 4463 | .get_output(&task_id, true, 3000) |
| 4464 | .expect("get_output must complete, not hang"); |
| 4465 | assert_eq!(done.status, ShellStatus::Completed); |
| 4466 | } |
| 4467 | |
| 4468 | #[cfg(unix)] |
| 4469 | #[test] |
| 4470 | fn foreground_shell_does_not_block_on_orphaned_subprocess_pipe() { |
| 4471 | let tmp = tempdir().expect("tempdir"); |
| 4472 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4473 | |
| 4474 | let started = std::time::Instant::now(); |
| 4475 | let result = execute_shell(&mut manager, "sh -c 'sleep 100 &'", None, 5000, false) |
| 4476 | .expect("foreground execute must complete, not hang"); |
| 4477 | |
| 4478 | assert!( |
| 4479 | started.elapsed() < std::time::Duration::from_secs(4), |
| 4480 | "foreground execute blocked on descendant pipe handles" |
| 4481 | ); |
| 4482 | assert_eq!(result.status, ShellStatus::Completed); |
| 4483 | } |
| 4484 | |
| 4485 | // Windows equivalent of the orphaned pipe-handle regression. `cmd /c start /b` |
| 4486 | // launches a descendant process that inherits stdout/stderr and outlives the |
| 4487 | // shell. Job-object cleanup must terminate that descendant before reader-thread |
| 4488 | // joins, otherwise get_output() blocks until ping exits. |
| 4489 | #[cfg(windows)] |
| 4490 | #[test] |
| 4491 | fn background_collection_does_not_block_on_detached_descendant_pipe() { |
| 4492 | let tmp = tempdir().expect("tempdir"); |
| 4493 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4494 | |
| 4495 | let result = execute_shell( |
| 4496 | &mut manager, |
| 4497 | r#"cmd /c start "" /b ping 127.0.0.1 -n 4"#, |
| 4498 | None, |
| 4499 | 5000, |
| 4500 | true, |
| 4501 | ) |
| 4502 | .expect("execute"); |
| 4503 | let task_id = result.task_id.expect("task id"); |
| 4504 | |
| 4505 | let started = std::time::Instant::now(); |
| 4506 | let done = manager |
| 4507 | .get_output(&task_id, true, 3000) |
| 4508 | .expect("get_output must complete, not hang"); |
| 4509 | |
| 4510 | assert!( |
| 4511 | started.elapsed() < std::time::Duration::from_secs(6), |
| 4512 | "get_output blocked on descendant pipe handles" |
| 4513 | ); |
| 4514 | assert_eq!(done.status, ShellStatus::Completed); |
| 4515 | } |
| 4516 | |
| 4517 | #[cfg(windows)] |
| 4518 | #[test] |
| 4519 | fn windows_job_terminate_denied_falls_back_to_child_kill() { |
| 4520 | let mut child = Command::new("ping") |
| 4521 | .args(["127.0.0.1", "-n", "20"]) |
| 4522 | .stdin(Stdio::null()) |
| 4523 | .stdout(Stdio::null()) |
| 4524 | .stderr(Stdio::null()) |
| 4525 | .spawn() |
| 4526 | .expect("spawn ping"); |
| 4527 | |
| 4528 | let job = WindowsJob::attach_to_child(&child).expect("attach job"); |
| 4529 | let limited_job = duplicate_job_without_terminate_access(job); |
| 4530 | |
| 4531 | assert!( |
| 4532 | limited_job.terminate().is_err(), |
| 4533 | "limited job handle should not allow TerminateJobObject" |
| 4534 | ); |
| 4535 | |
| 4536 | terminate_child_and_close_windows_job(Some(limited_job), &mut child) |
| 4537 | .expect("fallback child kill"); |
| 4538 | |
| 4539 | let status = child |
| 4540 | .wait_timeout(std::time::Duration::from_secs(3)) |
| 4541 | .expect("wait after fallback kill"); |
| 4542 | assert!( |
| 4543 | status.is_some(), |
| 4544 | "fallback child kill should terminate child" |
| 4545 | ); |
| 4546 | } |
| 4547 | |
| 4548 | #[cfg(windows)] |
| 4549 | #[test] |
| 4550 | fn windows_job_close_releases_foreground_reader_threads_when_terminate_denied() { |
| 4551 | let mut child = Command::new("ping") |
| 4552 | .args(["127.0.0.1", "-n", "8"]) |
| 4553 | .stdin(Stdio::null()) |
| 4554 | .stdout(Stdio::piped()) |
| 4555 | .stderr(Stdio::piped()) |
| 4556 | .spawn() |
| 4557 | .expect("spawn ping"); |
| 4558 | |
| 4559 | let job = WindowsJob::attach_to_child(&child).expect("attach job"); |
| 4560 | let limited_job = duplicate_job_without_terminate_access(job); |
| 4561 | assert!( |
| 4562 | limited_job.terminate().is_err(), |
| 4563 | "limited job handle should not allow TerminateJobObject" |
| 4564 | ); |
| 4565 | |
| 4566 | let stdout_handle = child.stdout.take().expect("stdout pipe"); |
| 4567 | let stderr_handle = child.stderr.take().expect("stderr pipe"); |
| 4568 | let stdout_thread = std::thread::spawn(move || { |
| 4569 | let mut reader = stdout_handle; |
| 4570 | let mut buf = Vec::new(); |
| 4571 | let _ = reader.read_to_end(&mut buf); |
| 4572 | buf |
| 4573 | }); |
| 4574 | let stderr_thread = std::thread::spawn(move || { |
| 4575 | let mut reader = stderr_handle; |
| 4576 | let mut buf = Vec::new(); |
| 4577 | let _ = reader.read_to_end(&mut buf); |
| 4578 | buf |
| 4579 | }); |
| 4580 | |
| 4581 | let started = std::time::Instant::now(); |
| 4582 | terminate_and_close_windows_job(Some(limited_job)); |
| 4583 | let _ = stdout_thread.join().unwrap_or_default(); |
| 4584 | let _ = stderr_thread.join().unwrap_or_default(); |
| 4585 | let status = child |
| 4586 | .wait_timeout(std::time::Duration::from_secs(3)) |
| 4587 | .expect("wait after kill-on-close"); |
| 4588 | |
| 4589 | assert!( |
| 4590 | started.elapsed() < std::time::Duration::from_secs(4), |
| 4591 | "reader joins waited for natural descendant exit instead of kill-on-close" |
| 4592 | ); |
| 4593 | assert!(status.is_some(), "kill-on-close should terminate child"); |
| 4594 | } |
| 4595 | |
| 4596 | #[cfg(windows)] |
| 4597 | #[test] |
| 4598 | fn windows_job_kill_on_close_releases_reader_threads_when_terminate_denied() { |
| 4599 | let tmp = tempdir().expect("tempdir"); |
| 4600 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4601 | |
| 4602 | let result = execute_shell( |
| 4603 | &mut manager, |
| 4604 | r#"cmd /c start "" /b ping 127.0.0.1 -n 60"#, |
| 4605 | None, |
| 4606 | 5000, |
| 4607 | true, |
| 4608 | ) |
| 4609 | .expect("execute"); |
| 4610 | let task_id = result.task_id.expect("task id"); |
| 4611 | |
| 4612 | { |
| 4613 | let shell = manager |
| 4614 | .processes |
| 4615 | .get_mut(&task_id) |
| 4616 | .expect("background shell"); |
| 4617 | let job = shell.windows_job.take().expect("windows job attached"); |
| 4618 | let limited_job = duplicate_job_without_terminate_access(job); |
| 4619 | assert!( |
| 4620 | limited_job.terminate().is_err(), |
| 4621 | "limited job handle should not allow TerminateJobObject" |
| 4622 | ); |
| 4623 | shell.windows_job = Some(limited_job); |
| 4624 | } |
| 4625 | |
| 4626 | let started = std::time::Instant::now(); |
| 4627 | let done = manager |
| 4628 | .get_output(&task_id, true, 20000) |
| 4629 | .expect("get_output must complete via kill-on-close fallback"); |
| 4630 | |
| 4631 | assert!( |
| 4632 | started.elapsed() < std::time::Duration::from_secs(30), |
| 4633 | "get_output waited for natural descendant exit instead of kill-on-close" |
| 4634 | ); |
| 4635 | assert_eq!(done.status, ShellStatus::Completed); |
| 4636 | } |
| 4637 | |
| 4638 | #[cfg(windows)] |
| 4639 | #[test] |
| 4640 | fn killed_shell_does_not_wait_for_blocked_reader_threads() { |
| 4641 | let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); |
| 4642 | let stdout_thread = std::thread::spawn(move || { |
| 4643 | let _ = release_rx.recv(); |
| 4644 | }); |
| 4645 | let now = std::time::Instant::now(); |
| 4646 | let mut shell = BackgroundShell { |
| 4647 | id: "killed-reader".to_string(), |
| 4648 | owner_session_id: "windows-test-session".to_string(), |
| 4649 | command: "test".to_string(), |
| 4650 | description: None, |
| 4651 | working_dir: std::path::PathBuf::from("."), |
| 4652 | status: ShellStatus::Killed, |
| 4653 | exit_code: None, |
| 4654 | started_at: now, |
| 4655 | started_at_utc: chrono::Utc::now(), |
| 4656 | finished_at: Some(now), |
| 4657 | finished_at_utc: Some(chrono::Utc::now()), |
| 4658 | cause: Some(ShellTerminationCause::Killed), |
| 4659 | background: true, |
| 4660 | last_output_at: now, |
| 4661 | last_observed_output_len: 0, |
| 4662 | sandbox_type: SandboxType::None, |
| 4663 | ownership: ShellOwnership::Managed, |
| 4664 | linked_task_id: None, |
| 4665 | owner_agent: None, |
| 4666 | origin_tool_call_id: None, |
| 4667 | origin_turn_id: None, |
| 4668 | stdout_buffer: super::new_shared_raw_output(), |
| 4669 | stderr_buffer: None, |
| 4670 | heavy_permit: None, |
| 4671 | scratch: None, |
| 4672 | stdout_cursor: 0, |
| 4673 | stderr_cursor: 0, |
| 4674 | completion_reported: false, |
| 4675 | bounded_output: None, |
| 4676 | stdin: None, |
| 4677 | pty_master: None, |
| 4678 | terminal_size: None, |
| 4679 | child: None, |
| 4680 | windows_job: None, |
| 4681 | stdout_thread: Some(stdout_thread), |
| 4682 | stderr_thread: None, |
| 4683 | work_lifecycle: None, |
| 4684 | lifecycle_seq: 0, |
| 4685 | last_lifecycle_status: None, |
| 4686 | last_lifecycle_bytes: 0, |
| 4687 | wait_failed: false, |
| 4688 | terminal_exit_confirmed: false, |
| 4689 | hold: None, |
| 4690 | }; |
| 4691 | |
| 4692 | let started = std::time::Instant::now(); |
| 4693 | shell.finish_child(); |
| 4694 | |
| 4695 | assert!( |
| 4696 | started.elapsed() < std::time::Duration::from_secs(1), |
| 4697 | "killed shell must not synchronously join a blocked reader" |
| 4698 | ); |
| 4699 | release_tx.send(()).expect("release detached reader"); |
| 4700 | } |
| 4701 | |
| 4702 | #[test] |
| 4703 | fn test_list_jobs_cleans_up_completed_old_processes() { |
| 4704 | let tmp = tempdir().expect("tempdir"); |
| 4705 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4706 | |
| 4707 | let bg = |
| 4708 | execute_shell(&mut manager, &echo_command("bg"), None, 5000, true).expect("execute bg"); |
| 4709 | let bg_id = bg.task_id.expect("bg task id"); |
| 4710 | manager.get_output(&bg_id, true, 3000).expect("bg done"); |
| 4711 | |
| 4712 | // Both the completed job and any tracking state should be present. |
| 4713 | assert!(!manager.processes.is_empty()); |
| 4714 | |
| 4715 | // cleanup(ZERO) removes every delivered completed process immediately. |
| 4716 | manager.drain_finished_jobs_with_evidence(); |
| 4717 | manager.cleanup(Duration::ZERO); |
| 4718 | assert!( |
| 4719 | manager.processes.is_empty(), |
| 4720 | "completed processes should be evicted by cleanup" |
| 4721 | ); |
| 4722 | } |
| 4723 | |
| 4724 | /// A job that ran longer than the retention age must survive until its |
| 4725 | /// completion is delivered: age counts from the finish, not the start. |
| 4726 | #[test] |
| 4727 | fn cleanup_ages_jobs_from_finish() { |
| 4728 | let tmp = tempdir().expect("tempdir"); |
| 4729 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4730 | let long_run = FINISHED_SHELL_MAX_AGE + Duration::from_secs(600); |
| 4731 | manager.seed_finished_record_for_test("long-job", long_run); |
| 4732 | |
| 4733 | // Started 70 minutes ago, finished just now, not yet delivered. |
| 4734 | manager.list_jobs(); |
| 4735 | assert!( |
| 4736 | manager.inspect_job("long-job").is_ok(), |
| 4737 | "a long job must not be evicted the moment it finishes" |
| 4738 | ); |
| 4739 | let delivered = manager.drain_finished_jobs_with_evidence(); |
| 4740 | assert_eq!(delivered.len(), 1, "the completion must still be delivered"); |
| 4741 | assert_eq!(delivered[0].event.task_id, "long-job"); |
| 4742 | |
| 4743 | // Delivered and recently finished: still inside the retention window. |
| 4744 | manager.cleanup(FINISHED_SHELL_MAX_AGE); |
| 4745 | assert!(manager.inspect_job("long-job").is_ok()); |
| 4746 | |
| 4747 | // Delivered and finished longer ago than the window: evicted. |
| 4748 | let shell = manager.processes.get_mut("long-job").expect("record"); |
| 4749 | shell.finished_at = Instant::now().checked_sub(long_run); |
| 4750 | manager.cleanup(FINISHED_SHELL_MAX_AGE); |
| 4751 | assert!(manager.inspect_job("long-job").is_err()); |
| 4752 | } |
| 4753 | |
| 4754 | /// Nothing ever drains a completion owned by a Runtime API scope or by a |
| 4755 | /// session that is no longer active, so an undelivered job must still age out |
| 4756 | /// (counted from when it finished) instead of staying until the count cap. |
| 4757 | #[test] |
| 4758 | fn cleanup_ages_out_undelivered_completions_after_finish() { |
| 4759 | let tmp = tempdir().expect("tempdir"); |
| 4760 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4761 | let max_age = Duration::from_secs(30); |
| 4762 | manager.seed_finished_record_for_test("api-job", Duration::from_secs(50)); |
| 4763 | let shell = manager.processes.get_mut("api-job").expect("record"); |
| 4764 | shell.owner_session_id = "api:thread-1".to_string(); |
| 4765 | shell.finished_at = Instant::now().checked_sub(Duration::from_secs(40)); |
| 4766 | assert!(!shell.completion_reported); |
| 4767 | |
| 4768 | manager.cleanup(max_age); |
| 4769 | assert!( |
| 4770 | manager.inspect_job("api-job").is_err(), |
| 4771 | "an undelivered completion finished longer ago than max_age must age out" |
| 4772 | ); |
| 4773 | } |
| 4774 | |
| 4775 | /// The count ceiling evicts the records that finished longest ago, the same |
| 4776 | /// clock the age rule uses: a long job that just finished is not "oldest". |
| 4777 | #[test] |
| 4778 | fn finished_job_bounds_evict_by_finish_time() { |
| 4779 | let tmp = tempdir().expect("tempdir"); |
| 4780 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4781 | let now = Instant::now(); |
| 4782 | for index in 0..MAX_FINISHED_SHELL_RECORDS { |
| 4783 | let id = format!("short-{index:03}"); |
| 4784 | // Started 20 s ago, finished 10 s ago. |
| 4785 | manager.seed_finished_record_for_test(id.clone(), Duration::from_secs(20)); |
| 4786 | let shell = manager.processes.get_mut(&id).expect("record"); |
| 4787 | shell.finished_at = now.checked_sub(Duration::from_secs(10)); |
| 4788 | shell.completion_reported = true; |
| 4789 | } |
| 4790 | // Started 60 s ago, finished just now. |
| 4791 | manager.seed_finished_record_for_test("long-job", Duration::from_secs(60)); |
| 4792 | manager |
| 4793 | .processes |
| 4794 | .get_mut("long-job") |
| 4795 | .expect("record") |
| 4796 | .completion_reported = true; |
| 4797 | |
| 4798 | manager.cleanup(FINISHED_SHELL_MAX_AGE); |
| 4799 | assert_eq!(manager.tracked_job_count(), MAX_FINISHED_SHELL_RECORDS); |
| 4800 | assert!( |
| 4801 | manager.inspect_job("long-job").is_ok(), |
| 4802 | "the most recently finished job was evicted first" |
| 4803 | ); |
| 4804 | } |
| 4805 | |
| 4806 | #[cfg(unix)] |
| 4807 | #[test] |
| 4808 | fn foreground_shell_reaps_child_on_stdin_failure() { |
| 4809 | let workspace = tempdir().expect("tempdir"); |
| 4810 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 4811 | let input = "x".repeat(2 * 1024 * 1024); |
| 4812 | let err = manager |
| 4813 | .execute_with_options_env( |
| 4814 | "echo $$ > helper.pid; exec 0<&-; exec sleep 9", |
| 4815 | None, |
| 4816 | 15_000, |
| 4817 | false, |
| 4818 | Some(&input), |
| 4819 | false, |
| 4820 | None, |
| 4821 | HashMap::new(), |
| 4822 | ) |
| 4823 | .expect_err("closed stdin"); |
| 4824 | assert!( |
| 4825 | err.to_string().contains("Failed to write to stdin"), |
| 4826 | "{err}" |
| 4827 | ); |
| 4828 | let pid = wait_for_shell_pid_file(&workspace.path().join("helper.pid")); |
| 4829 | assert!( |
| 4830 | wait_for_shell_pid_exit(pid), |
| 4831 | "foreground child is still present" |
| 4832 | ); |
| 4833 | } |
| 4834 | |
| 4835 | /// The synchronous path closes stdin when there is no input: `cat` gets EOF |
| 4836 | /// instead of reading, or blocking on, Codewhale's own stdin. |
| 4837 | #[cfg(unix)] |
| 4838 | #[test] |
| 4839 | fn sync_command_without_input_gets_eof_not_inherited_stdin() { |
| 4840 | let tmp = tempdir().expect("tempdir"); |
| 4841 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4842 | let started = Instant::now(); |
| 4843 | let result = manager |
| 4844 | .execute_with_options_env( |
| 4845 | "cat; echo after-eof", |
| 4846 | None, |
| 4847 | 15_000, |
| 4848 | false, |
| 4849 | None, |
| 4850 | false, |
| 4851 | None, |
| 4852 | HashMap::new(), |
| 4853 | ) |
| 4854 | .expect("run"); |
| 4855 | assert!( |
| 4856 | started.elapsed() < Duration::from_secs(10), |
| 4857 | "stdin read blocked for {:?}", |
| 4858 | started.elapsed() |
| 4859 | ); |
| 4860 | assert!(result.stdout.contains("after-eof"), "{}", result.stdout); |
| 4861 | } |
| 4862 | |
| 4863 | /// A backgrounded lowercase `bash` job: each read returns only output the |
| 4864 | /// caller has not seen, not the whole retained tail again. |
| 4865 | #[cfg(unix)] |
| 4866 | #[test] |
| 4867 | fn bounded_job_delta_returns_only_new_output() { |
| 4868 | let tmp = tempdir().expect("tempdir"); |
| 4869 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 4870 | let started = manager |
| 4871 | .execute_with_options_env_for_owner_and_work( |
| 4872 | "printf 'first-chunk\\n'; while [ ! -e go ]; do sleep 0.05; done; printf 'second-chunk\\n'", |
| 4873 | None, |
| 4874 | None, |
| 4875 | 60_000, |
| 4876 | true, |
| 4877 | None, |
| 4878 | false, |
| 4879 | None, |
| 4880 | HashMap::new(), |
| 4881 | None, |
| 4882 | String::new(), |
| 4883 | None, |
| 4884 | None, |
| 4885 | None, |
| 4886 | None, |
| 4887 | false, |
| 4888 | (1, BASH_MAX_TIMEOUT_MS), |
| 4889 | ) |
| 4890 | .expect("spawn bounded job"); |
| 4891 | let task_id = started.task_id.expect("task id"); |
| 4892 | assert!( |
| 4893 | manager.processes[&task_id].bounded_output.is_some(), |
| 4894 | "fixture must exercise the bounded accumulator" |
| 4895 | ); |
| 4896 | |
| 4897 | let deadline = Instant::now() + Duration::from_secs(10); |
| 4898 | let mut seen = String::new(); |
| 4899 | while !seen.contains("first-chunk") { |
| 4900 | assert!(Instant::now() < deadline, "first chunk never arrived"); |
| 4901 | let delta = manager |
| 4902 | .get_output_delta(&task_id, false, 0) |
| 4903 | .expect("first delta"); |
| 4904 | seen.push_str(&delta.result.stdout); |
| 4905 | std::thread::sleep(Duration::from_millis(20)); |
| 4906 | } |
| 4907 | assert_eq!(seen.matches("first-chunk").count(), 1, "{seen}"); |
| 4908 | // The fixture writes its second chunk only now, so the first delta cannot |
| 4909 | // have raced past it. |
| 4910 | std::fs::write(tmp.path().join("go"), "").expect("release fixture"); |
| 4911 | |
| 4912 | let rest = manager |
| 4913 | .get_output_delta(&task_id, true, 10_000) |
| 4914 | .expect("remaining delta"); |
| 4915 | assert_ne!(rest.result.status, ShellStatus::Running); |
| 4916 | assert!( |
| 4917 | rest.result.stdout.contains("second-chunk"), |
| 4918 | "{}", |
| 4919 | rest.result.stdout |
| 4920 | ); |
| 4921 | assert!( |
| 4922 | !rest.result.stdout.contains("first-chunk"), |
| 4923 | "a delta must not repeat output already returned: {:?}", |
| 4924 | rest.result.stdout |
| 4925 | ); |
| 4926 | } |
| 4927 | |
| 4928 | /// A foreground command that reads stdin gets EOF instead of blocking until |
| 4929 | /// the timeout kills it. |
| 4930 | #[cfg(unix)] |
| 4931 | #[tokio::test] |
| 4932 | async fn foreground_command_reading_stdin_gets_eof() { |
| 4933 | let tmp = tempdir().expect("tempdir"); |
| 4934 | let ctx = ToolContext::new(tmp.path()); |
| 4935 | let started = Instant::now(); |
| 4936 | let result = BashTool::new("Bash") |
| 4937 | .execute( |
| 4938 | json!({"command": "cat; echo after-eof", "timeout_ms": 15_000}), |
| 4939 | &ctx, |
| 4940 | ) |
| 4941 | .await |
| 4942 | .expect("execute"); |
| 4943 | assert!( |
| 4944 | started.elapsed() < Duration::from_secs(10), |
| 4945 | "stdin read blocked for {:?}", |
| 4946 | started.elapsed() |
| 4947 | ); |
| 4948 | assert!(result.content.contains("after-eof"), "{}", result.content); |
| 4949 | } |
| 4950 | |
| 4951 | /// Regression for #1691: a `git commit -m "feat: complete sub-pages"` shell |
| 4952 | /// command must reach the OS shell with its quoted message intact (one argv |
| 4953 | /// slot), never split into `feat:` / `complete` / `sub-pages"`. |
| 4954 | #[test] |
| 4955 | fn issue_1691_quoted_commit_message_round_trips() { |
| 4956 | let cmd = r#"git commit -m "feat: complete sub-pages""#; |
| 4957 | let spec = CommandSpec::shell( |
| 4958 | cmd, |
| 4959 | std::path::PathBuf::from("/tmp"), |
| 4960 | Duration::from_secs(5), |
| 4961 | ); |
| 4962 | |
| 4963 | let dispatcher = codewhale_sandbox::shell_dispatcher::global_dispatcher(); |
| 4964 | // The whole command (with quotes) is a single argv entry. The actual |
| 4965 | // shell binary can vary by platform — and the dispatcher may wrap the |
| 4966 | // payload (encoding prefix, exit-code capture) — but the payload itself |
| 4967 | // must stay intact in ONE shell arg. We never split the command string |
| 4968 | // ourselves. This single-line ASCII command never takes the PowerShell |
| 4969 | // temp `-File` path, so the payload stays on the argv. |
| 4970 | assert_eq!(spec.program, dispatcher.kind().binary()); |
| 4971 | let carriers = spec |
| 4972 | .args |
| 4973 | .iter() |
| 4974 | .filter(|arg| arg.contains(r#""feat: complete sub-pages""#)) |
| 4975 | .count(); |
| 4976 | assert_eq!(carriers, 1, "args: {:?}", spec.args); |
| 4977 | assert!( |
| 4978 | !spec |
| 4979 | .args |
| 4980 | .iter() |
| 4981 | .any(|arg| arg == "feat:" || arg == "complete" || arg == "sub-pages\""), |
| 4982 | "args: {:?}", |
| 4983 | spec.args |
| 4984 | ); |
| 4985 | assert_eq!(spec.display_command(), cmd); |
| 4986 | |
| 4987 | let mut built = Command::new(&spec.program); |
| 4988 | push_shell_args(&mut built, &spec.program, &spec.args); |
| 4989 | let got: Vec<String> = built |
| 4990 | .get_args() |
| 4991 | .map(|a| a.to_string_lossy().into_owned()) |
| 4992 | .collect(); |
| 4993 | assert_eq!(got, spec.args); |
| 4994 | } |
| 4995 | |
| 4996 | /// When no `cwd` is provided, the shell should run in `context.workspace`, |
| 4997 | /// not in the ShellManager's default_workspace. This ensures sub-agents in |
| 4998 | /// worktrees run commands in the worktree directory rather than the parent. |
| 4999 | /// |
| 5000 | /// Without the `context.workspace` default (stashed): runs in sm_dir → FAILS |
| 5001 | /// With the `context.workspace` default (unstashed): runs in ctx_dir → PASSES |
| 5002 | #[tokio::test] |
| 5003 | async fn default_cwd_uses_context_workspace_not_shell_manager_default() { |
| 5004 | let ctx_dir = tempdir().expect("ctx tempdir"); |
| 5005 | let sm_dir = tempdir().expect("sm tempdir"); |
| 5006 | |
| 5007 | // Create distinct dirs — write a marker in each so we can tell them apart. |
| 5008 | std::fs::write(ctx_dir.path().join("I_AM_CTX_DIR"), "").unwrap(); |
| 5009 | std::fs::write(sm_dir.path().join("I_AM_SM_DIR"), "").unwrap(); |
| 5010 | |
| 5011 | // ToolContext whose workspace is ctx_dir... |
| 5012 | let ctx = ToolContext::new(ctx_dir.path()) |
| 5013 | // ...but whose ShellManager's default_workspace is sm_dir. |
| 5014 | .with_shell_manager(new_shared_shell_manager(sm_dir.path().to_path_buf())); |
| 5015 | |
| 5016 | // Assert directory identity through marker files instead of comparing the |
| 5017 | // shell's printed path. PowerShell and `canonicalize` can spell the same |
| 5018 | // Windows path differently (for example, with a verbatim-path prefix). |
| 5019 | let command = if cfg!(windows) { |
| 5020 | "if (Test-Path -LiteralPath 'I_AM_CTX_DIR') { Write-Output 'context-workspace' } elseif (Test-Path -LiteralPath 'I_AM_SM_DIR') { Write-Output 'manager-workspace' } else { Write-Output 'missing-workspace' }" |
| 5021 | } else { |
| 5022 | "if [ -f I_AM_CTX_DIR ]; then printf 'context-workspace'; elif [ -f I_AM_SM_DIR ]; then printf 'manager-workspace'; else printf 'missing-workspace'; fi" |
| 5023 | }; |
| 5024 | let result = BashTool::new("Bash") |
| 5025 | .execute(json!({"command": command}), &ctx) |
| 5026 | .await |
| 5027 | .expect("shell execute"); |
| 5028 | assert!(result.success, "command failed: {:?}", result.content); |
| 5029 | |
| 5030 | assert!( |
| 5031 | result |
| 5032 | .content |
| 5033 | .lines() |
| 5034 | .any(|line| line.trim() == "context-workspace"), |
| 5035 | "expected context.workspace marker, but shell reported: {:?}", |
| 5036 | result.content |
| 5037 | ); |
| 5038 | } |
| 5039 | |
| 5040 | // ── Kill-path overshoot regression tests (FINISH-0.9.4 #52 multiplier 2) ───── |
| 5041 | // |
| 5042 | // The foreground Bash kill path must return at ~timeout + a small bounded |
| 5043 | // grace, even when the command ignores SIGTERM or a descendant escapes the |
| 5044 | // process group while holding the output pipe open. Before the fix, an |
| 5045 | // escaped descendant wedged the blocking reader-thread join inside kill() |
| 5046 | // until the descendant exited on its own (observed: ~180s past a 120s |
| 5047 | // timeout in the wild). |
| 5048 | |
| 5049 | #[cfg(unix)] |
| 5050 | const SHELL_SIGTERM_HELPER_ENV: &str = "CODEWHALE_SHELL_SIGTERM_HELPER"; |
| 5051 | #[cfg(unix)] |
| 5052 | const SHELL_ESCAPE_HELPER_ENV: &str = "CODEWHALE_SHELL_ESCAPE_HELPER"; |
| 5053 | #[cfg(unix)] |
| 5054 | const SHELL_ESCAPED_GRANDCHILD_ENV: &str = "CODEWHALE_SHELL_ESCAPED_GRANDCHILD"; |
| 5055 | |
| 5056 | /// Helper role: ignore SIGTERM and idle. Runs as the shell's direct child |
| 5057 | /// (same process group), so only the SIGKILL escalation can stop it. |
| 5058 | #[cfg(unix)] |
| 5059 | #[test] |
| 5060 | fn shell_sigterm_ignoring_helper_process() { |
| 5061 | if std::env::var(SHELL_SIGTERM_HELPER_ENV).ok().as_deref() != Some("1") { |
| 5062 | return; |
| 5063 | } |
| 5064 | unsafe { |
| 5065 | libc::signal(libc::SIGTERM, libc::SIG_IGN); |
| 5066 | } |
| 5067 | let pid_file = PathBuf::from( |
| 5068 | std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("sigterm helper pid file"), |
| 5069 | ); |
| 5070 | std::fs::write(pid_file, std::process::id().to_string()).expect("write sigterm helper pid"); |
| 5071 | loop { |
| 5072 | std::thread::sleep(Duration::from_millis(10)); |
| 5073 | } |
| 5074 | } |
| 5075 | |
| 5076 | /// Helper role: spawn a grandchild in its OWN process group (escaping the |
| 5077 | /// shell's group) that inherits the output pipe, then exit immediately. The |
| 5078 | /// wrapper shell keeps running (`sleep` after `&`), so the job stays Running |
| 5079 | /// while the escaped grandchild holds the reader thread's pipe open. |
| 5080 | #[cfg(unix)] |
| 5081 | // The grandchild deliberately outlives this helper and is never wait()ed on — |
| 5082 | // escaping reaping is exactly what the regression exercises; the test reaps |
| 5083 | // it directly via SIGKILL at the end. |
| 5084 | #[allow(clippy::zombie_processes)] |
| 5085 | #[test] |
| 5086 | fn shell_group_escape_helper_process() { |
| 5087 | if std::env::var(SHELL_ESCAPE_HELPER_ENV).ok().as_deref() != Some("1") { |
| 5088 | return; |
| 5089 | } |
| 5090 | let test_binary = std::env::current_exe().expect("current test binary"); |
| 5091 | let pid_file = std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("escape pid file"); |
| 5092 | let mut cmd = Command::new(test_binary); |
| 5093 | cmd.arg("--exact") |
| 5094 | .arg("tools::shell::tests::shell_escaped_grandchild_helper_process") |
| 5095 | .arg("--nocapture") |
| 5096 | .env(SHELL_ESCAPED_GRANDCHILD_ENV, "1") |
| 5097 | .env(SHELL_DESCENDANT_PID_FILE_ENV, pid_file); |
| 5098 | // A distinct process group is enough to escape `kill(-wrapper_pgid)`; |
| 5099 | // stdout/stderr are inherited, so the grandchild keeps the pipe open. |
| 5100 | #[cfg(unix)] |
| 5101 | cmd.process_group(0); |
| 5102 | let _child = cmd.spawn().expect("spawn escaped grandchild"); |
| 5103 | } |
| 5104 | |
| 5105 | /// Helper role: the escaped grandchild — ignores SIGTERM, reports its pid, |
| 5106 | /// then idles (holding the inherited output pipe open the whole time). |
| 5107 | #[cfg(unix)] |
| 5108 | #[test] |
| 5109 | fn shell_escaped_grandchild_helper_process() { |
| 5110 | if std::env::var(SHELL_ESCAPED_GRANDCHILD_ENV).ok().as_deref() != Some("1") { |
| 5111 | return; |
| 5112 | } |
| 5113 | unsafe { |
| 5114 | libc::signal(libc::SIGTERM, libc::SIG_IGN); |
| 5115 | } |
| 5116 | let pid_file = |
| 5117 | PathBuf::from(std::env::var(SHELL_DESCENDANT_PID_FILE_ENV).expect("grandchild pid file")); |
| 5118 | std::fs::write(pid_file, std::process::id().to_string()).expect("write grandchild pid"); |
| 5119 | std::thread::sleep(Duration::from_secs(30)); |
| 5120 | } |
| 5121 | |
| 5122 | /// Regression for the ~180s kill-path overshoot: a descendant that escaped |
| 5123 | /// the process group keeps the output pipe open after the group is killed. |
| 5124 | /// kill() must still return within a bounded grace instead of blocking on |
| 5125 | /// the reader-thread join until the descendant exits on its own. |
| 5126 | #[cfg(unix)] |
| 5127 | #[tokio::test] |
| 5128 | async fn kill_returns_promptly_when_escaped_descendant_holds_pipe_open() { |
| 5129 | let tmp = tempdir().expect("tempdir"); |
| 5130 | let pid_file = tmp.path().join("escaped-grandchild.pid"); |
| 5131 | let test_binary = std::env::current_exe().expect("current test binary"); |
| 5132 | let command = format!( |
| 5133 | "{SHELL_ESCAPE_HELPER_ENV}=1 {SHELL_DESCENDANT_PID_FILE_ENV}={} {} --exact {} --nocapture & sleep 60", |
| 5134 | shell_words::quote(&pid_file.display().to_string()), |
| 5135 | shell_words::quote(&test_binary.display().to_string()), |
| 5136 | shell_words::quote("tools::shell::tests::shell_group_escape_helper_process"), |
| 5137 | ); |
| 5138 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 5139 | let started_bg = |
| 5140 | execute_shell(&mut manager, &command, None, 600_000, true).expect("start wrapper"); |
| 5141 | let task_id = started_bg.task_id.expect("task id"); |
| 5142 | let grandchild = wait_for_shell_pid_file(&pid_file); |
| 5143 | |
| 5144 | let started = Instant::now(); |
| 5145 | let killed = manager.kill(&task_id).expect("kill"); |
| 5146 | let wall = started.elapsed(); |
| 5147 | |
| 5148 | assert_eq!(killed.status, ShellStatus::Killed); |
| 5149 | assert!( |
| 5150 | wall < Duration::from_secs(10), |
| 5151 | "kill blocked {wall:?} on a reader wedged by an escaped descendant" |
| 5152 | ); |
| 5153 | |
| 5154 | // Cleanup: the escaped grandchild is out of reach of the group kill by |
| 5155 | // construction; reap it directly so the test does not leak a sleeper. |
| 5156 | unsafe { |
| 5157 | libc::kill(grandchild, libc::SIGKILL); |
| 5158 | } |
| 5159 | assert!(wait_for_shell_pid_exit(grandchild)); |
| 5160 | } |
| 5161 | |
| 5162 | /// `Bash` was the only action wrapper whose catch-all fell through to its most |
| 5163 | /// dangerous branch: an unrecognised action ran the command instead. |
| 5164 | #[tokio::test] |
| 5165 | async fn unknown_bash_action_is_refused_instead_of_running_the_command() { |
| 5166 | let workspace = tempdir().expect("workspace"); |
| 5167 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5168 | let marker = workspace.path().join("should-not-exist"); |
| 5169 | |
| 5170 | let error = BashTool::new("Bash") |
| 5171 | .execute( |
| 5172 | json!({ |
| 5173 | "action": "kill", |
| 5174 | "command": format!("touch {}", marker.display()), |
| 5175 | }), |
| 5176 | &context, |
| 5177 | ) |
| 5178 | .await |
| 5179 | .expect_err("unknown action must be refused"); |
| 5180 | |
| 5181 | let message = error.to_string(); |
| 5182 | assert!(message.contains("Unknown Bash action"), "{message}"); |
| 5183 | assert!(message.contains("kill"), "{message}"); |
| 5184 | assert!( |
| 5185 | message.contains("run, wait, interact, cancel"), |
| 5186 | "must name the actions that dispatch: {message}" |
| 5187 | ); |
| 5188 | assert!(!marker.exists(), "the command must not have run"); |
| 5189 | } |
| 5190 | |
| 5191 | /// A NUL byte cannot cross the `exec` boundary: `Command` panics on it. |
| 5192 | /// Refuse with the byte offset before anything spawns (#5529). |
| 5193 | #[tokio::test] |
| 5194 | async fn nul_byte_in_shell_command_is_refused_before_spawn() { |
| 5195 | let workspace = tempdir().expect("workspace"); |
| 5196 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5197 | let marker = workspace.path().join("should-not-exist"); |
| 5198 | |
| 5199 | let error = BashTool::new("Bash") |
| 5200 | .execute( |
| 5201 | json!({ |
| 5202 | "command": format!("echo hi\0; touch {}", marker.display()), |
| 5203 | }), |
| 5204 | &context, |
| 5205 | ) |
| 5206 | .await |
| 5207 | .expect_err("NUL byte must be refused"); |
| 5208 | |
| 5209 | let message = error.to_string(); |
| 5210 | assert!(message.contains("NUL byte"), "{message}"); |
| 5211 | assert!(message.contains("byte offset 7"), "{message}"); |
| 5212 | assert!(!marker.exists(), "the command must not have run"); |
| 5213 | } |
| 5214 | |
| 5215 | /// `cwd` crosses the same boundary via `current_dir`, so the guard covers it |
| 5216 | /// too (#5529). |
| 5217 | #[tokio::test] |
| 5218 | async fn nul_byte_in_shell_cwd_is_refused_before_spawn() { |
| 5219 | let workspace = tempdir().expect("workspace"); |
| 5220 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5221 | |
| 5222 | let error = BashTool::new("Bash") |
| 5223 | .execute( |
| 5224 | json!({ |
| 5225 | "command": "echo hi", |
| 5226 | "cwd": "sub\0dir", |
| 5227 | }), |
| 5228 | &context, |
| 5229 | ) |
| 5230 | .await |
| 5231 | .expect_err("NUL byte must be refused"); |
| 5232 | |
| 5233 | let message = error.to_string(); |
| 5234 | assert!(message.contains("NUL byte"), "{message}"); |
| 5235 | assert!(message.contains("cwd"), "{message}"); |
| 5236 | assert!(message.contains("byte offset 3"), "{message}"); |
| 5237 | } |
| 5238 | |
| 5239 | /// The same hole one type down. `and_then(as_str).unwrap_or("run")` read a |
| 5240 | /// non-string `action` as absent and fell through to the branch that executes |
| 5241 | /// arbitrary code, so `Bash{action: 3, command: "…"}` ran the command. `File`, |
| 5242 | /// `Git`, `Web`, and `Run` all refuse a non-string action; the tool that runs |
| 5243 | /// shell commands must not be the lenient one. |
| 5244 | #[tokio::test] |
| 5245 | async fn non_string_bash_action_is_refused_instead_of_running_the_command() { |
| 5246 | let workspace = tempdir().expect("workspace"); |
| 5247 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5248 | |
| 5249 | for action in [json!(3), json!(true), json!(["run"]), json!({"run": true})] { |
| 5250 | let marker = workspace.path().join(format!("marker-{action}")); |
| 5251 | let error = BashTool::new("Bash") |
| 5252 | .execute( |
| 5253 | json!({ |
| 5254 | "action": action, |
| 5255 | "command": format!("touch {}", marker.display()), |
| 5256 | }), |
| 5257 | &context, |
| 5258 | ) |
| 5259 | .await |
| 5260 | .expect_err("a non-string action must be refused"); |
| 5261 | |
| 5262 | let message = error.to_string(); |
| 5263 | assert!( |
| 5264 | message.contains("'action'"), |
| 5265 | "must name the parameter: {message}" |
| 5266 | ); |
| 5267 | assert!( |
| 5268 | message.contains("must be a string"), |
| 5269 | "must name the expected type: {message}" |
| 5270 | ); |
| 5271 | assert!(!marker.exists(), "the command must not have run: {action}"); |
| 5272 | } |
| 5273 | } |
| 5274 | |
| 5275 | /// The same hole for the data fields (2026-08-04 review). A non-string |
| 5276 | /// `stdin` was silently dropped — the command ran with NO stdin and reported |
| 5277 | /// success, the silent-drop failure this lane exists to close. A non-string |
| 5278 | /// `cwd` silently ran in the workspace default. And a numeric `task_id` was |
| 5279 | /// reported as "missing", steering the model's retry the wrong way. |
| 5280 | #[tokio::test] |
| 5281 | async fn wrongly_typed_stdin_cwd_and_task_id_are_refused_not_dropped() { |
| 5282 | let workspace = tempdir().expect("workspace"); |
| 5283 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5284 | |
| 5285 | let marker = workspace.path().join("stdin-marker"); |
| 5286 | let error = BashTool::new("Bash") |
| 5287 | .execute( |
| 5288 | json!({ |
| 5289 | "command": format!("touch {}", marker.display()), |
| 5290 | "stdin": 12345, |
| 5291 | }), |
| 5292 | &context, |
| 5293 | ) |
| 5294 | .await |
| 5295 | .expect_err("non-string stdin must be refused, never silently dropped"); |
| 5296 | let message = error.to_string(); |
| 5297 | assert!(message.contains("'stdin'"), "names the field: {message}"); |
| 5298 | assert!( |
| 5299 | message.contains("must be a string"), |
| 5300 | "names the expected type: {message}" |
| 5301 | ); |
| 5302 | assert!(!marker.exists(), "the command must not have run"); |
| 5303 | |
| 5304 | let error = BashTool::new("Bash") |
| 5305 | .execute(json!({ "command": "pwd", "cwd": 123 }), &context) |
| 5306 | .await |
| 5307 | .expect_err("non-string cwd must be refused, never defaulted"); |
| 5308 | assert!(error.to_string().contains("'cwd'"), "{error}"); |
| 5309 | |
| 5310 | let error = BashTool::new("Bash") |
| 5311 | .execute(json!({ "action": "wait", "task_id": 42 }), &context) |
| 5312 | .await |
| 5313 | .expect_err("non-string task_id is a type error"); |
| 5314 | let message = error.to_string(); |
| 5315 | assert!( |
| 5316 | message.contains("'task_id'") && message.contains("must be a string"), |
| 5317 | "a supplied-but-mistyped task_id must not read as missing: {message}" |
| 5318 | ); |
| 5319 | } |
| 5320 | |
| 5321 | /// `null` is the wire spelling of absence, and `action` documents a `run` |
| 5322 | /// default — so the strictness above must not swallow the default. |
| 5323 | #[tokio::test] |
| 5324 | async fn absent_or_null_bash_action_still_defaults_to_run() { |
| 5325 | let workspace = tempdir().expect("workspace"); |
| 5326 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5327 | |
| 5328 | for input in [ |
| 5329 | json!({"command": "echo defaulted"}), |
| 5330 | json!({"action": null, "command": "echo defaulted"}), |
| 5331 | ] { |
| 5332 | let result = BashTool::new("Bash") |
| 5333 | .execute(input.clone(), &context) |
| 5334 | .await |
| 5335 | .unwrap_or_else(|err| panic!("{input} must still run: {err}")); |
| 5336 | assert!(result.success, "{input}: {}", result.content); |
| 5337 | assert!(result.content.contains("defaulted"), "{}", result.content); |
| 5338 | } |
| 5339 | } |
| 5340 | |
| 5341 | /// Negative case for the strictness above: every legitimate action still |
| 5342 | /// dispatches to its own handler rather than the action refusal. `wait`, |
| 5343 | /// `interact`, and `cancel` are checked by the error they raise *after* |
| 5344 | /// dispatch (a missing/unknown task), which only their own handlers produce. |
| 5345 | #[tokio::test] |
| 5346 | async fn every_valid_bash_action_still_dispatches() { |
| 5347 | let workspace = tempdir().expect("workspace"); |
| 5348 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5349 | let tool = BashTool::new("Bash"); |
| 5350 | |
| 5351 | let ran = tool |
| 5352 | .execute( |
| 5353 | json!({"action": "run", "command": "echo dispatched"}), |
| 5354 | &context, |
| 5355 | ) |
| 5356 | .await |
| 5357 | .expect("action=run must dispatch"); |
| 5358 | assert!(ran.success, "{}", ran.content); |
| 5359 | |
| 5360 | for input in [ |
| 5361 | json!({"action": "wait", "task_id": "no-such-task"}), |
| 5362 | json!({"action": "interact", "task_id": "no-such-task", "stdin": "y\n"}), |
| 5363 | json!({"action": "cancel", "task_id": "no-such-task"}), |
| 5364 | ] { |
| 5365 | let outcome = tool.execute(input.clone(), &context).await; |
| 5366 | let message = match outcome { |
| 5367 | Ok(result) => result.content, |
| 5368 | Err(err) => err.to_string(), |
| 5369 | }; |
| 5370 | assert!( |
| 5371 | !message.contains("Unknown Bash action") && !message.contains("must be a string"), |
| 5372 | "{input} must reach its own handler, got: {message}" |
| 5373 | ); |
| 5374 | } |
| 5375 | |
| 5376 | // `cancel` with `all` needs no task at all and must stay a success. |
| 5377 | let cancelled = tool |
| 5378 | .execute(json!({"action": "cancel", "all": true}), &context) |
| 5379 | .await |
| 5380 | .expect("action=cancel all=true must dispatch"); |
| 5381 | assert!(cancelled.success, "{}", cancelled.content); |
| 5382 | } |
| 5383 | |
| 5384 | /// The stdin aliases were real but undocumented: a model that wrote `input` |
| 5385 | /// or `data` got them honoured with nothing in the schema saying so, and a |
| 5386 | /// maintainer reading the schema would have removed them as dead. Advertise |
| 5387 | /// them, and hold every spelling to the same behavior. |
| 5388 | #[tokio::test] |
| 5389 | async fn every_advertised_stdin_spelling_reaches_the_command() { |
| 5390 | let workspace = tempdir().expect("workspace"); |
| 5391 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5392 | let schema = BashTool::new("Bash").input_schema(); |
| 5393 | |
| 5394 | // `cat` is Unix-only; the dispatcher runs PowerShell or `cmd` on Windows, |
| 5395 | // where it is either absent or an alias for `Get-Content`, which reads a |
| 5396 | // file and not stdin. Ask for this platform's echo-stdin spelling — the |
| 5397 | // same helper `test_write_stdin_streams_output` uses. |
| 5398 | let echo_stdin = echo_stdin_command(); |
| 5399 | for spelling in ["stdin", "input", "data"] { |
| 5400 | assert!( |
| 5401 | schema["properties"][spelling].is_object(), |
| 5402 | "`{spelling}` is honoured at runtime and must be advertised" |
| 5403 | ); |
| 5404 | let result = BashTool::new("Bash") |
| 5405 | .execute( |
| 5406 | json!({"command": echo_stdin, spelling: "PIPED_THROUGH_ALIAS\n"}), |
| 5407 | &context, |
| 5408 | ) |
| 5409 | .await |
| 5410 | .unwrap_or_else(|err| panic!("`{spelling}` must deliver stdin: {err}")); |
| 5411 | assert!( |
| 5412 | result.content.contains("PIPED_THROUGH_ALIAS"), |
| 5413 | "`{spelling}` did not reach the command: {}", |
| 5414 | result.content |
| 5415 | ); |
| 5416 | } |
| 5417 | |
| 5418 | // `id` is the same undocumented shape one parameter over. |
| 5419 | assert!( |
| 5420 | schema["properties"]["id"].is_object(), |
| 5421 | "`id` is accepted for `task_id` at runtime and must be advertised" |
| 5422 | ); |
| 5423 | assert!( |
| 5424 | schema["properties"]["task_id"]["description"] |
| 5425 | .as_str() |
| 5426 | .is_some_and(|text| text.contains("`id`")), |
| 5427 | "task_id must name its alias" |
| 5428 | ); |
| 5429 | } |
| 5430 | |
| 5431 | /// The schema declared no `required` key at all, so `Bash{}` — no command, no |
| 5432 | /// task — was schema-valid for the tool that runs shell commands. What is |
| 5433 | /// required is per-action, so it is spelled as root `anyOf` required groups, |
| 5434 | /// the same shape `apply_patch` already uses. |
| 5435 | #[test] |
| 5436 | fn bash_schema_declares_what_each_action_requires() { |
| 5437 | let schema = BashTool::new("Bash").input_schema(); |
| 5438 | let groups: Vec<Vec<String>> = schema["anyOf"] |
| 5439 | .as_array() |
| 5440 | .expect("root anyOf required groups") |
| 5441 | .iter() |
| 5442 | .map(|group| { |
| 5443 | group["required"] |
| 5444 | .as_array() |
| 5445 | .expect("required group") |
| 5446 | .iter() |
| 5447 | .map(|name| name.as_str().expect("required name").to_string()) |
| 5448 | .collect() |
| 5449 | }) |
| 5450 | .collect(); |
| 5451 | |
| 5452 | for expected in [["command"], ["task_id"], ["id"], ["all"]] { |
| 5453 | assert!( |
| 5454 | groups.iter().any(|group| group.as_slice() == expected), |
| 5455 | "missing required group {expected:?} in {groups:?}" |
| 5456 | ); |
| 5457 | } |
| 5458 | // A required name the same schema does not advertise would be |
| 5459 | // unsatisfiable: the model could not learn what to send. |
| 5460 | for group in &groups { |
| 5461 | for name in group { |
| 5462 | assert!( |
| 5463 | schema["properties"][name].is_object(), |
| 5464 | "`{name}` is required but not advertised" |
| 5465 | ); |
| 5466 | } |
| 5467 | } |
| 5468 | } |
| 5469 | |
| 5470 | /// A root `anyOf` is not portable to every provider, so prove the fallback |
| 5471 | /// the sanitizer promises: Responses/xAI drop root composition, and the |
| 5472 | /// constraint has to survive as a description note rather than vanishing. |
| 5473 | #[test] |
| 5474 | fn bash_required_groups_survive_a_provider_that_drops_root_composition() { |
| 5475 | let mut schema = BashTool::new("Bash").input_schema(); |
| 5476 | let note = codewhale_models::schema_sanitize::sanitize_for_responses(&mut schema) |
| 5477 | .expect("dropped required groups must be restated for the model"); |
| 5478 | |
| 5479 | assert!(note.contains("At least one"), "{note}"); |
| 5480 | for name in ["`command`", "`task_id`", "`id`", "`all`"] { |
| 5481 | assert!(note.contains(name), "note must name {name}: {note}"); |
| 5482 | } |
| 5483 | assert_eq!(schema["type"], "object"); |
| 5484 | assert!(schema.get("anyOf").is_none(), "root anyOf must be removed"); |
| 5485 | assert!(schema["properties"]["command"].is_object()); |
| 5486 | } |
| 5487 | |
| 5488 | /// One documented default hid three real ones: `wait` uses 30s and |
| 5489 | /// `interact` 1s, so a model omitting `timeout_ms` on `wait` got a quarter of |
| 5490 | /// the timeout the schema promised. |
| 5491 | #[test] |
| 5492 | fn timeout_ms_description_covers_every_action_default() { |
| 5493 | let schema = BashTool::new("Bash").input_schema(); |
| 5494 | let description = schema["properties"]["timeout_ms"]["description"] |
| 5495 | .as_str() |
| 5496 | .expect("timeout_ms description"); |
| 5497 | |
| 5498 | for expected in ["600000", "30000", "1000"] { |
| 5499 | assert!( |
| 5500 | description.contains(expected), |
| 5501 | "missing {expected}: {description}" |
| 5502 | ); |
| 5503 | } |
| 5504 | } |
| 5505 | |
| 5506 | #[cfg(unix)] |
| 5507 | fn authorized_persistent_service_context(workspace: &Path) -> ToolContext { |
| 5508 | let mut context = ToolContext::new(workspace.to_path_buf()) |
| 5509 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::DangerFullAccess); |
| 5510 | context.persist_services_enabled = true; |
| 5511 | context.tool_authority = None; |
| 5512 | context.shell_policy = ShellPolicy::Full; |
| 5513 | context.auto_approve = true; |
| 5514 | context |
| 5515 | } |
| 5516 | |
| 5517 | #[cfg(unix)] |
| 5518 | fn persistent_service_test_lock() -> &'static tokio::sync::Mutex<()> { |
| 5519 | static LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new(); |
| 5520 | LOCK.get_or_init(|| tokio::sync::Mutex::new(())) |
| 5521 | } |
| 5522 | |
| 5523 | #[cfg(unix)] |
| 5524 | #[tokio::test] |
| 5525 | async fn persistent_service_requires_explicit_headless_exec_authority() { |
| 5526 | let workspace = tempdir().expect("workspace"); |
| 5527 | let context = ToolContext::new(workspace.path().to_path_buf()); |
| 5528 | |
| 5529 | let error = BashTool::new("Bash") |
| 5530 | .execute( |
| 5531 | json!({ |
| 5532 | "action": "run", |
| 5533 | "command": "sleep 30", |
| 5534 | "background": true, |
| 5535 | "persist": true, |
| 5536 | }), |
| 5537 | &context, |
| 5538 | ) |
| 5539 | .await |
| 5540 | .expect_err("ordinary tool contexts must reject ownership transfer"); |
| 5541 | |
| 5542 | assert!(error.to_string().contains("Full Access shell authority")); |
| 5543 | } |
| 5544 | |
| 5545 | #[cfg(not(target_env = "ohos"))] |
| 5546 | #[test] |
| 5547 | fn failed_wait_retains_the_child_until_exit_is_observed() { |
| 5548 | let workspace = tempdir().unwrap(); |
| 5549 | let mut manager = ShellManager::new(workspace.path().into()); |
| 5550 | manager.seed_finished_record_for_test("pending-exit", Duration::ZERO); |
| 5551 | let mut child = std::process::Command::new(if cfg!(windows) { "sort.exe" } else { "sort" }) |
| 5552 | .stdin(std::process::Stdio::piped()) |
| 5553 | .stdout(std::process::Stdio::null()) |
| 5554 | .stderr(std::process::Stdio::null()) |
| 5555 | .spawn() |
| 5556 | .unwrap(); |
| 5557 | let input = child.stdin.take().unwrap(); |
| 5558 | let shell = manager.processes.get_mut("pending-exit").unwrap(); |
| 5559 | shell.child = Some(ShellChild::Pty(Box::new(child))); |
| 5560 | shell.status = ShellStatus::Failed; |
| 5561 | shell.wait_failed = true; |
| 5562 | shell.finish_child(); |
| 5563 | manager.pin_job_receipt("pending-exit").unwrap(); |
| 5564 | manager.cleanup(Duration::ZERO); |
| 5565 | assert_eq!(manager.unsettled_owned_job_count(), 1); |
| 5566 | drop(input); |
| 5567 | let deadline = Instant::now() + Duration::from_secs(10); |
| 5568 | while manager.unsettled_owned_job_count() > 0 { |
| 5569 | assert!(Instant::now() < deadline, "expected to observe sort's exit"); |
| 5570 | std::thread::sleep(Duration::from_millis(10)); |
| 5571 | } |
| 5572 | manager.cleanup(Duration::ZERO); |
| 5573 | let witness = manager.job_receipt_witness("pending-exit").unwrap(); |
| 5574 | assert!(witness.wait_failed); |
| 5575 | assert!(!witness.terminal_confirmed); |
| 5576 | } |
| 5577 | |
| 5578 | #[cfg(unix)] |
| 5579 | #[tokio::test] |
| 5580 | async fn committed_persistent_service_survives_manager_drop_and_reports_identity() { |
| 5581 | let _guard = persistent_service_test_lock().lock().await; |
| 5582 | let workspace = tempdir().expect("workspace"); |
| 5583 | let marker = workspace.path().join("persistent-service-finished"); |
| 5584 | let context = authorized_persistent_service_context(workspace.path()); |
| 5585 | |
| 5586 | let result = BashTool::new("Bash") |
| 5587 | .execute( |
| 5588 | json!({ |
| 5589 | "action": "run", |
| 5590 | "command": format!("sleep 1; printf released > '{}'", marker.display()), |
| 5591 | "background": true, |
| 5592 | "persist": true, |
| 5593 | }), |
| 5594 | &context, |
| 5595 | ) |
| 5596 | .await |
| 5597 | .expect("stage persistent service"); |
| 5598 | assert!(result.success, "{result:?}"); |
| 5599 | assert_eq!( |
| 5600 | result |
| 5601 | .metadata |
| 5602 | .as_ref() |
| 5603 | .and_then(|metadata| metadata["ownership"].as_str()), |
| 5604 | Some("managed_pending_exec_success") |
| 5605 | ); |
| 5606 | let task_id = result.metadata.as_ref().unwrap()["task_id"] |
| 5607 | .as_str() |
| 5608 | .expect("task id") |
| 5609 | .to_string(); |
| 5610 | |
| 5611 | let receipts = { |
| 5612 | let mut manager = context.shell_manager.lock().expect("shell manager"); |
| 5613 | assert_eq!(manager.unsettled_owned_job_count(), 1); |
| 5614 | let receipts = manager |
| 5615 | .commit_persistent_services() |
| 5616 | .expect("commit persistent service"); |
| 5617 | assert_eq!(manager.unsettled_owned_job_count(), 0); |
| 5618 | receipts |
| 5619 | }; |
| 5620 | assert_eq!(receipts.len(), 1); |
| 5621 | assert_eq!(receipts[0].task_id, task_id); |
| 5622 | assert_eq!(receipts[0].process_group_id, receipts[0].pid); |
| 5623 | assert_eq!(receipts[0].ownership, "external"); |
| 5624 | |
| 5625 | drop(context); |
| 5626 | let deadline = Instant::now() + Duration::from_secs(5); |
| 5627 | while !marker.exists() && Instant::now() < deadline { |
| 5628 | std::thread::sleep(Duration::from_millis(25)); |
| 5629 | } |
| 5630 | assert!( |
| 5631 | marker.exists(), |
| 5632 | "released service must survive Codewhale manager teardown" |
| 5633 | ); |
| 5634 | } |
| 5635 | |
| 5636 | #[cfg(unix)] |
| 5637 | #[tokio::test] |
| 5638 | async fn signal_cleanup_kills_staged_persistent_service_group() { |
| 5639 | let _guard = persistent_service_test_lock().lock().await; |
| 5640 | let workspace = tempdir().expect("workspace"); |
| 5641 | let context = authorized_persistent_service_context(workspace.path()); |
| 5642 | |
| 5643 | let result = BashTool::new("Bash") |
| 5644 | .execute( |
| 5645 | json!({ |
| 5646 | "action": "run", |
| 5647 | "command": "sleep 30", |
| 5648 | "background": true, |
| 5649 | "persist": true, |
| 5650 | }), |
| 5651 | &context, |
| 5652 | ) |
| 5653 | .await |
| 5654 | .expect("stage persistent service"); |
| 5655 | let task_id = result.metadata.as_ref().unwrap()["task_id"] |
| 5656 | .as_str() |
| 5657 | .expect("task id") |
| 5658 | .to_string(); |
| 5659 | let pid = context |
| 5660 | .shell_manager |
| 5661 | .lock() |
| 5662 | .expect("shell manager") |
| 5663 | .processes[&task_id] |
| 5664 | .child |
| 5665 | .as_ref() |
| 5666 | .and_then(ShellChild::process_id) |
| 5667 | .expect("persistent process id"); |
| 5668 | |
| 5669 | abort_pending_persistent_process_groups_for_exit(); |
| 5670 | let pid = i32::try_from(pid).expect("pid fits pid_t"); |
| 5671 | let deadline = Instant::now() + Duration::from_secs(2); |
| 5672 | let status = loop { |
| 5673 | let mut status = 0; |
| 5674 | // SAFETY: `pid` is the direct child owned by this test's manager; the |
| 5675 | // nonblocking wait only reaps that exact process. |
| 5676 | let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) }; |
| 5677 | if waited == pid { |
| 5678 | break status; |
| 5679 | } |
| 5680 | assert!( |
| 5681 | Instant::now() < deadline, |
| 5682 | "signal cleanup must kill the staged service process group" |
| 5683 | ); |
| 5684 | std::thread::sleep(Duration::from_millis(25)); |
| 5685 | }; |
| 5686 | assert!(libc::WIFSIGNALED(status)); |
| 5687 | assert_eq!(libc::WTERMSIG(status), libc::SIGKILL); |
| 5688 | } |
| 5689 | |
| 5690 | // === #5472: in-memory retention must be bounded === |
| 5691 | |
| 5692 | /// ~1.1 MB on stdout, fast: 30,000 lines of 37 bytes. |
| 5693 | #[cfg(unix)] |
| 5694 | fn chatty_command() -> String { |
| 5695 | "yes 0123456789abcdefghijklmnopqrstuvwxyz | head -n 30000".to_string() |
| 5696 | } |
| 5697 | |
| 5698 | /// The finding-1 regression: before this bound, a single uppercase `Bash` call |
| 5699 | /// left its entire stdout resident in `ShellManager.processes` until the 1 h |
| 5700 | /// `cleanup`, and only if the user happened to open the jobs panel. |
| 5701 | #[cfg(unix)] |
| 5702 | #[tokio::test] |
| 5703 | async fn foreground_bash_releases_its_output_once_the_result_is_returned() { |
| 5704 | let tmp = tempdir().expect("tempdir"); |
| 5705 | let ctx = ToolContext::new(tmp.path()); |
| 5706 | let result = BashTool::new("Bash") |
| 5707 | .execute(json!({"command": chatty_command()}), &ctx) |
| 5708 | .await |
| 5709 | .expect("run chatty foreground command"); |
| 5710 | |
| 5711 | // The result itself is unaffected: still the same 30 KB truncation. |
| 5712 | assert!( |
| 5713 | result |
| 5714 | .content |
| 5715 | .contains("0123456789abcdefghijklmnopqrstuvwxyz") |
| 5716 | ); |
| 5717 | |
| 5718 | let manager = ctx.shell_manager.lock().expect("shell manager"); |
| 5719 | let retained = manager.retained_output_bytes_total(); |
| 5720 | assert!( |
| 5721 | retained <= RAW_STREAM_SETTLED_TAIL_BYTES * 2, |
| 5722 | "a finished foreground call must not keep its full stdout resident: \ |
| 5723 | {retained} bytes still held (bound {})", |
| 5724 | RAW_STREAM_SETTLED_TAIL_BYTES * 2 |
| 5725 | ); |
| 5726 | } |
| 5727 | |
| 5728 | /// Releasing memory must not rewrite history: the job panel keeps reporting how |
| 5729 | /// much the command actually printed. |
| 5730 | #[cfg(unix)] |
| 5731 | #[tokio::test] |
| 5732 | async fn released_output_still_reports_the_real_stream_length() { |
| 5733 | let tmp = tempdir().expect("tempdir"); |
| 5734 | let ctx = ToolContext::new(tmp.path()); |
| 5735 | BashTool::new("Bash") |
| 5736 | .execute(json!({"command": chatty_command()}), &ctx) |
| 5737 | .await |
| 5738 | .expect("run chatty foreground command"); |
| 5739 | |
| 5740 | let mut manager = ctx.shell_manager.lock().expect("shell manager"); |
| 5741 | let jobs = manager.list_jobs(); |
| 5742 | let job = jobs.first().expect("the finished job is still listed"); |
| 5743 | assert!( |
| 5744 | job.stdout_len >= 1_000_000, |
| 5745 | "stdout_len must stay honest after release, got {}", |
| 5746 | job.stdout_len |
| 5747 | ); |
| 5748 | assert!( |
| 5749 | !job.stdout_tail.is_empty(), |
| 5750 | "a diagnostic tail must survive the release" |
| 5751 | ); |
| 5752 | } |
| 5753 | |
| 5754 | /// A background job's bytes become a durable session artifact at drain time; |
| 5755 | /// keeping a second copy in the manager afterwards is the pure-waste term. |
| 5756 | #[cfg(unix)] |
| 5757 | #[tokio::test] |
| 5758 | async fn draining_completion_evidence_releases_the_retained_copy() { |
| 5759 | let tmp = tempdir().expect("tempdir"); |
| 5760 | let ctx = ToolContext::new(tmp.path()); |
| 5761 | let started = BashTool::new("Bash") |
| 5762 | .execute( |
| 5763 | json!({"command": chatty_command(), "background": true}), |
| 5764 | &ctx, |
| 5765 | ) |
| 5766 | .await |
| 5767 | .expect("start background"); |
| 5768 | let task_id = started |
| 5769 | .metadata |
| 5770 | .as_ref() |
| 5771 | .and_then(|metadata| metadata.get("task_id")) |
| 5772 | .and_then(Value::as_str) |
| 5773 | .expect("task id") |
| 5774 | .to_string(); |
| 5775 | |
| 5776 | let mut manager = ctx.shell_manager.lock().expect("shell manager"); |
| 5777 | let completed = wait_for_completed_shell(&mut manager, &task_id); |
| 5778 | assert_ne!(completed.status, ShellStatus::Running); |
| 5779 | |
| 5780 | let evidence = manager.drain_finished_jobs_with_evidence(); |
| 5781 | assert_eq!(evidence.len(), 1); |
| 5782 | assert!( |
| 5783 | evidence[0].event.stdout_len >= 1_000_000, |
| 5784 | "the event still reports the full length" |
| 5785 | ); |
| 5786 | let payload: serde_json::Value = |
| 5787 | serde_json::from_slice(&evidence[0].artifact_bytes()).expect("evidence JSON"); |
| 5788 | assert!( |
| 5789 | payload["stdout"]["content"] |
| 5790 | .as_str() |
| 5791 | .expect("stdout content") |
| 5792 | .len() |
| 5793 | >= 1_000_000, |
| 5794 | "the artifact carries the exact bytes; only the manager's copy is dropped" |
| 5795 | ); |
| 5796 | |
| 5797 | let retained = manager.retained_output_bytes_total(); |
| 5798 | assert!( |
| 5799 | retained <= RAW_STREAM_SETTLED_TAIL_BYTES * 2, |
| 5800 | "{retained} bytes still held after the evidence was published" |
| 5801 | ); |
| 5802 | } |
| 5803 | |
| 5804 | /// Age was the only bound, and it only ran from `list_jobs()`. Hundreds of |
| 5805 | /// finished records inside one hour were all retained. |
| 5806 | #[test] |
| 5807 | fn cleanup_bounds_finished_records_by_count() { |
| 5808 | let tmp = tempdir().expect("tempdir"); |
| 5809 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 5810 | let seeded_count = MAX_FINISHED_SHELL_RECORDS + 40; |
| 5811 | for index in 0..seeded_count { |
| 5812 | // Give every fixture a deterministic ordering while keeping all of |
| 5813 | // them far younger than the age ceiling. Lower ids are older. |
| 5814 | manager.seed_finished_record_for_test( |
| 5815 | format!("record-{index}"), |
| 5816 | Duration::from_millis((seeded_count - index) as u64), |
| 5817 | ); |
| 5818 | } |
| 5819 | manager.cleanup(FINISHED_SHELL_MAX_AGE); |
| 5820 | assert_eq!(manager.tracked_job_count(), MAX_FINISHED_SHELL_RECORDS); |
| 5821 | assert!( |
| 5822 | manager.inspect_job("record-39").is_err(), |
| 5823 | "the oldest overflow record must be evicted" |
| 5824 | ); |
| 5825 | assert!( |
| 5826 | manager.inspect_job("record-40").is_ok(), |
| 5827 | "the first record inside the cap must survive" |
| 5828 | ); |
| 5829 | assert!( |
| 5830 | manager |
| 5831 | .inspect_job(&format!("record-{}", seeded_count - 1)) |
| 5832 | .is_ok(), |
| 5833 | "the newest record must survive" |
| 5834 | ); |
| 5835 | } |
| 5836 | |
| 5837 | /// #5478 nit: `/jobs` reported `2m 07s` for a 12-second command, because |
| 5838 | /// elapsed was `started_at.elapsed()` even after the job finished. A completed |
| 5839 | /// job reports the duration it finished with. |
| 5840 | #[test] |
| 5841 | fn a_finished_job_reports_its_duration_not_a_growing_elapsed() { |
| 5842 | let tmp = tempdir().expect("tempdir"); |
| 5843 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 5844 | let result = manager |
| 5845 | .execute_with_options_env( |
| 5846 | &echo_command("frozen-elapsed"), |
| 5847 | None, |
| 5848 | 10_000, |
| 5849 | true, |
| 5850 | None, |
| 5851 | false, |
| 5852 | None, |
| 5853 | std::collections::HashMap::new(), |
| 5854 | ) |
| 5855 | .expect("spawn"); |
| 5856 | let task_id = result.task_id.expect("task id"); |
| 5857 | let completed = wait_for_completed_shell(&mut manager, &task_id); |
| 5858 | assert_ne!(completed.status, ShellStatus::Running); |
| 5859 | |
| 5860 | let first = manager |
| 5861 | .list_jobs() |
| 5862 | .into_iter() |
| 5863 | .find(|job| job.id == task_id) |
| 5864 | .expect("job listed") |
| 5865 | .elapsed_ms; |
| 5866 | |
| 5867 | std::thread::sleep(Duration::from_millis(400)); |
| 5868 | |
| 5869 | let second = manager |
| 5870 | .list_jobs() |
| 5871 | .into_iter() |
| 5872 | .find(|job| job.id == task_id) |
| 5873 | .expect("job still listed") |
| 5874 | .elapsed_ms; |
| 5875 | |
| 5876 | assert_eq!( |
| 5877 | first, second, |
| 5878 | "a finished job's elapsed must stop moving; it read {first}ms then {second}ms" |
| 5879 | ); |
| 5880 | assert!( |
| 5881 | second < 10_000, |
| 5882 | "the frozen value must be the real duration, not the timeout: {second}ms" |
| 5883 | ); |
| 5884 | } |
| 5885 | |
| 5886 | #[cfg(unix)] |
| 5887 | #[tokio::test] |
| 5888 | async fn readonly_pipeline_preserves_arguments_and_disables_git_helpers() { |
| 5889 | const PROBE: &str = "CODEWHALE_TEST_READONLY_PIPELINE_SHELL"; |
| 5890 | if std::env::var_os(PROBE).is_none() { |
| 5891 | // The dispatcher is process-pinned. Exercise both the supported shell |
| 5892 | // and the fail-closed POSIX fallback without inheriting the CI shell. |
| 5893 | for shell in ["/bin/bash", "/bin/sh"] { |
| 5894 | let output = std::process::Command::new(std::env::current_exe().unwrap()) |
| 5895 | .args([ |
| 5896 | "--exact", |
| 5897 | "tools::shell::tests::readonly_pipeline_preserves_arguments_and_disables_git_helpers", |
| 5898 | "--test-threads=1", |
| 5899 | ]) |
| 5900 | .env(PROBE, shell) |
| 5901 | .env("SHELL", shell) |
| 5902 | .output() |
| 5903 | .unwrap(); |
| 5904 | assert!( |
| 5905 | output.status.success(), |
| 5906 | "read-only pipeline probe failed ({shell})\n{}\n{}", |
| 5907 | String::from_utf8_lossy(&output.stdout), |
| 5908 | String::from_utf8_lossy(&output.stderr) |
| 5909 | ); |
| 5910 | } |
| 5911 | return; |
| 5912 | } |
| 5913 | let workspace = tempdir().unwrap(); |
| 5914 | let outside = tempdir().unwrap(); |
| 5915 | let sentinel = outside.path().join("secret"); |
| 5916 | std::fs::write(&sentinel, "private-marker\n").unwrap(); |
| 5917 | std::os::unix::fs::symlink(&sentinel, workspace.path().join("linked-secret")).unwrap(); |
| 5918 | std::fs::write(workspace.path().join("input.txt"), "hello\n").unwrap(); |
| 5919 | for name in ["-i", "-e", "-f", "--output=changed", "-o"] { |
| 5920 | std::fs::write(workspace.path().join(name), "option-shaped filename\n").unwrap(); |
| 5921 | } |
| 5922 | let ctx = ToolContext::new(workspace.path()) |
| 5923 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 5924 | let tool = BashTool::new("Bash"); |
| 5925 | for command in ["sort * | cat", "sed -n 1p * | cat", "cat * | cat"] { |
| 5926 | // #6675: a word-leading unquoted `*` is refused before anything runs |
| 5927 | // (its matches could be option-shaped names like the ones above). |
| 5928 | let result = tool.execute(json!({"command": command}), &ctx).await; |
| 5929 | match result { |
| 5930 | Err(error) => assert!( |
| 5931 | error.to_string().contains("unquoted `*`"), |
| 5932 | "{command}: {error}" |
| 5933 | ), |
| 5934 | Ok(result) => panic!("{command} must be refused, ran: {}", result.content), |
| 5935 | } |
| 5936 | assert_eq!( |
| 5937 | std::fs::read_to_string(&sentinel).unwrap(), |
| 5938 | "private-marker\n" |
| 5939 | ); |
| 5940 | assert!(!workspace.path().join("changed").exists()); |
| 5941 | } |
| 5942 | let ordinary = tool |
| 5943 | .execute(json!({"command": "cat input.txt | wc -l"}), &ctx) |
| 5944 | .await |
| 5945 | .unwrap(); |
| 5946 | if std::env::var(PROBE).as_deref() == Ok("/bin/sh") { |
| 5947 | assert!(!ordinary.success); |
| 5948 | assert!( |
| 5949 | ordinary |
| 5950 | .content |
| 5951 | .contains("read-only pipelines and chains require bash or zsh") |
| 5952 | ); |
| 5953 | return; |
| 5954 | } |
| 5955 | assert!(ordinary.success, "{}", ordinary.content); |
| 5956 | assert!( |
| 5957 | tool.execute(json!({"command": "cat linked-secret | cat"}), &ctx) |
| 5958 | .await |
| 5959 | .is_err() |
| 5960 | ); |
| 5961 | let pipeline = hardened_readonly_script("git show HEAD | cat", workspace.path()).unwrap(); |
| 5962 | assert!(pipeline.contains("--no-ext-diff")); |
| 5963 | assert!(pipeline.contains("--no-textconv")); |
| 5964 | assert!(pipeline.contains("--no-show-signature")); |
| 5965 | } |
| 5966 | |
| 5967 | #[tokio::test] |
| 5968 | async fn readonly_sed_extra_options_never_mutate_files() { |
| 5969 | let workspace = tempdir().unwrap(); |
| 5970 | let source = workspace.path().join("input.txt"); |
| 5971 | std::fs::write(&source, "first\nsecond\n").unwrap(); |
| 5972 | let ctx = ToolContext::new(workspace.path()) |
| 5973 | .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly); |
| 5974 | for command in [ |
| 5975 | "sed -n 1p input.txt -i", |
| 5976 | "sed -n 1p -i.bak input.txt", |
| 5977 | "sed -n 1p -e 1e input.txt", |
| 5978 | "sed -n 1p -f script input.txt", |
| 5979 | ] { |
| 5980 | let error = BashTool::new("Bash") |
| 5981 | .execute(json!({"command": command}), &ctx) |
| 5982 | .await |
| 5983 | .expect_err("refused"); |
| 5984 | assert!( |
| 5985 | error.to_string().contains("[shell.readonly.command]"), |
| 5986 | "{command}: {error}" |
| 5987 | ); |
| 5988 | assert_eq!(std::fs::read_to_string(&source).unwrap(), "first\nsecond\n"); |
| 5989 | } |
| 5990 | let result = BashTool::new("Bash") |
| 5991 | .execute(json!({"command": "sed -n 1p input.txt"}), &ctx) |
| 5992 | .await |
| 5993 | .unwrap(); |
| 5994 | assert!(result.success, "{}", result.content); |
| 5995 | } |
| 5996 | |
| 5997 | /// A transiently busy Work-graph must not veto the command. |
| 5998 | /// |
| 5999 | /// `register_operation` acquires the To-do/Plan locks with a short try-lock |
| 6000 | /// spin. Before this guard existed, a shell call landing in that window failed |
| 6001 | /// outright with "To-do state is busy; operation was not registered" — observed |
| 6002 | /// twice in one live session, each time right after another tool call. The |
| 6003 | /// registration is the same bookkeeping whose `observe` half is already |
| 6004 | /// best-effort, so a busy state now degrades to an unbound run. |
| 6005 | #[tokio::test] |
| 6006 | async fn busy_work_graph_degrades_the_spawn_intent_instead_of_failing_it() { |
| 6007 | use crate::tools::plan::new_shared_plan_state; |
| 6008 | use crate::tools::todo::new_shared_todo_list; |
| 6009 | use crate::work_graph::new_shared_work_runtime; |
| 6010 | |
| 6011 | let todos = new_shared_todo_list(); |
| 6012 | let plan = new_shared_plan_state(); |
| 6013 | let lifecycle = || ShellWorkLifecycle { |
| 6014 | work: new_shared_work_runtime(todos.clone(), plan.clone()), |
| 6015 | session_id: "session-test".to_string(), |
| 6016 | }; |
| 6017 | |
| 6018 | // Control: with the graph free, the intent binds. |
| 6019 | let bound = ShellSpawnIntentGuard::new(Some(lifecycle()), "shell_free", "echo hi"); |
| 6020 | assert!( |
| 6021 | bound.lifecycle.is_some(), |
| 6022 | "a free work-graph must bind the spawn intent" |
| 6023 | ); |
| 6024 | |
| 6025 | // Busy: hold the To-do lock so the try-lock spin cannot win. |
| 6026 | let _held = todos.lock().await; |
| 6027 | // The raw register call still reports the busy state — this is exactly what |
| 6028 | // used to propagate out of the spawn path and fail the command. |
| 6029 | assert!( |
| 6030 | lifecycle() |
| 6031 | .register("shell_busy_direct", "echo hi") |
| 6032 | .is_err(), |
| 6033 | "the raw register call must observe the held lock as busy" |
| 6034 | ); |
| 6035 | let busy = ShellSpawnIntentGuard::new(Some(lifecycle()), "shell_busy", "echo hi"); |
| 6036 | assert!( |
| 6037 | busy.lifecycle.is_none(), |
| 6038 | "a busy work-graph must degrade to an unbound guard, not fail the spawn" |
| 6039 | ); |
| 6040 | } |
| 6041 | |
| 6042 | /// #6435: the guard went unbound, but its sibling handle still published the |
| 6043 | /// spawn to the unregistered operation, killed the child and reported |
| 6044 | /// "operation binding shell:<id> is not registered". A busy Work-graph must |
| 6045 | /// let the command run end to end. |
| 6046 | #[cfg(unix)] |
| 6047 | #[tokio::test] |
| 6048 | async fn busy_work_graph_still_runs_the_command() { |
| 6049 | use crate::tools::plan::new_shared_plan_state; |
| 6050 | use crate::tools::todo::new_shared_todo_list; |
| 6051 | use crate::work_graph::new_shared_work_runtime; |
| 6052 | |
| 6053 | let workspace = tempdir().expect("workspace"); |
| 6054 | let todos = new_shared_todo_list(); |
| 6055 | let plan = new_shared_plan_state(); |
| 6056 | let lifecycle = ShellWorkLifecycle { |
| 6057 | work: new_shared_work_runtime(todos.clone(), plan.clone()), |
| 6058 | session_id: "session-test".to_string(), |
| 6059 | }; |
| 6060 | let _held = todos.lock().await; |
| 6061 | let mut manager = ShellManager::new(workspace.path().to_path_buf()); |
| 6062 | for background in [false, true] { |
| 6063 | let marker = format!("ran-{background}.txt"); |
| 6064 | let result = manager |
| 6065 | .execute_with_options_env_for_owner_and_work( |
| 6066 | &format!("echo ran > {marker}"), |
| 6067 | None, |
| 6068 | None, |
| 6069 | 10_000, |
| 6070 | background, |
| 6071 | None, |
| 6072 | false, |
| 6073 | None, |
| 6074 | HashMap::new(), |
| 6075 | None, |
| 6076 | "session-test".to_string(), |
| 6077 | None, |
| 6078 | None, |
| 6079 | Some(lifecycle.clone()), |
| 6080 | None, |
| 6081 | false, |
| 6082 | (1_000, 60_000), |
| 6083 | ) |
| 6084 | .unwrap_or_else(|err| panic!("background={background}: {err:#}")); |
| 6085 | if background { |
| 6086 | let task_id = result.task_id.expect("background task id"); |
| 6087 | let deadline = std::time::Instant::now() + Duration::from_secs(10); |
| 6088 | while !workspace.path().join(&marker).exists() { |
| 6089 | assert!(std::time::Instant::now() < deadline, "{task_id} never ran"); |
| 6090 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 6091 | } |
| 6092 | } |
| 6093 | assert!( |
| 6094 | workspace.path().join(&marker).exists(), |
| 6095 | "background={background}: the command ran" |
| 6096 | ); |
| 6097 | } |
| 6098 | } |
| 6099 | |
| 6100 | #[test] |
| 6101 | fn pty_dimensions_reject_zero_and_unbounded_grid() { |
| 6102 | assert_eq!( |
| 6103 | PtyDimensions::default(), |
| 6104 | PtyDimensions { rows: 24, cols: 80 } |
| 6105 | ); |
| 6106 | for size in [ |
| 6107 | PtyDimensions { rows: 0, cols: 80 }, |
| 6108 | PtyDimensions { rows: 24, cols: 0 }, |
| 6109 | PtyDimensions { |
| 6110 | rows: 1001, |
| 6111 | cols: 80, |
| 6112 | }, |
| 6113 | PtyDimensions { |
| 6114 | rows: 24, |
| 6115 | cols: u16::MAX, |
| 6116 | }, |
| 6117 | ] { |
| 6118 | assert!(size.validate().is_err()); |
| 6119 | } |
| 6120 | assert!( |
| 6121 | PtyDimensions { |
| 6122 | rows: 1000, |
| 6123 | cols: 1000 |
| 6124 | } |
| 6125 | .validate() |
| 6126 | .is_ok() |
| 6127 | ); |
| 6128 | } |
| 6129 | |
| 6130 | #[test] |
| 6131 | #[cfg(not(target_env = "ohos"))] |
| 6132 | fn pty_stdin_preserves_bytes_and_reports_flush_failure() { |
| 6133 | struct FlushFailure(Arc<Mutex<Vec<u8>>>); |
| 6134 | impl Write for FlushFailure { |
| 6135 | fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { |
| 6136 | self.0.lock().unwrap().extend_from_slice(bytes); |
| 6137 | Ok(bytes.len()) |
| 6138 | } |
| 6139 | fn flush(&mut self) -> io::Result<()> { |
| 6140 | Err(io::Error::new( |
| 6141 | io::ErrorKind::BrokenPipe, |
| 6142 | "fixture flush failure", |
| 6143 | )) |
| 6144 | } |
| 6145 | } |
| 6146 | let tmp = tempdir().unwrap(); |
| 6147 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 6148 | manager.seed_finished_record_for_test("input-fixture", Duration::ZERO); |
| 6149 | let bytes = Arc::new(Mutex::new(Vec::new())); |
| 6150 | manager.processes.get_mut("input-fixture").unwrap().stdin = |
| 6151 | Some(StdinWriter::Pty(Box::new(FlushFailure(bytes.clone())))); |
| 6152 | let input = b"\0\xff\x1b[A\x03"; |
| 6153 | let error = manager |
| 6154 | .write_stdin_bytes("input-fixture", input, false) |
| 6155 | .unwrap_err(); |
| 6156 | assert!(error.to_string().contains("flush")); |
| 6157 | assert_eq!(bytes.lock().unwrap().as_slice(), input); |
| 6158 | } |
| 6159 | |
| 6160 | #[test] |
| 6161 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 6162 | fn pty_resize_updates_live_terminal_and_rejects_finished_or_pipe_jobs() { |
| 6163 | let tmp = tempdir().unwrap(); |
| 6164 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 6165 | let launched = manager |
| 6166 | .execute_with_options_env( |
| 6167 | "stty -echo; printf ready; while IFS= read -r line; do stty size; done", |
| 6168 | None, |
| 6169 | 5000, |
| 6170 | true, |
| 6171 | None, |
| 6172 | true, |
| 6173 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 6174 | HashMap::new(), |
| 6175 | ) |
| 6176 | .unwrap(); |
| 6177 | let id = launched.task_id.unwrap(); |
| 6178 | assert_eq!( |
| 6179 | manager.job_terminal_size(&id), |
| 6180 | Some(PtyDimensions::default()) |
| 6181 | ); |
| 6182 | let deadline = Instant::now() + Duration::from_secs(5); |
| 6183 | loop { |
| 6184 | let chunk = manager |
| 6185 | .read_output_chunk(&id, ShellOutputStream::Stdout, 0, 4096, 50) |
| 6186 | .unwrap(); |
| 6187 | if chunk.bytes.windows(5).any(|bytes| bytes == b"ready") { |
| 6188 | break; |
| 6189 | } |
| 6190 | assert!(Instant::now() < deadline, "PTY did not become ready"); |
| 6191 | } |
| 6192 | // Reopening a client after an idle minute must retain this live PTY's |
| 6193 | // identity and resize eligibility; output silence is normal at a prompt. |
| 6194 | manager.processes.get_mut(&id).unwrap().last_output_at = |
| 6195 | Instant::now() - QUIET_NO_OUTPUT_AFTER - Duration::from_millis(1); |
| 6196 | let idle = manager.inspect_job(&id).unwrap().snapshot; |
| 6197 | assert_eq!(idle.status, ShellStatus::Running); |
| 6198 | assert!(idle.stdin_available); |
| 6199 | assert!(!idle.stale, "an idle live PTY must remain reconnectable"); |
| 6200 | assert!( |
| 6201 | idle.elapsed_since_output_ms |
| 6202 | .is_some_and(|ms| ms >= QUIET_NO_OUTPUT_AFTER.as_millis() as u64) |
| 6203 | ); |
| 6204 | let size = PtyDimensions { |
| 6205 | rows: 37, |
| 6206 | cols: 111, |
| 6207 | }; |
| 6208 | manager.resize_pty(&id, size).unwrap(); |
| 6209 | assert_eq!(manager.job_terminal_size(&id), Some(size)); |
| 6210 | assert!( |
| 6211 | manager |
| 6212 | .resize_pty(&id, PtyDimensions { rows: 0, cols: 1 }) |
| 6213 | .is_err() |
| 6214 | ); |
| 6215 | assert_eq!(manager.job_terminal_size(&id), Some(size)); |
| 6216 | manager.write_stdin_bytes(&id, b"size\n", false).unwrap(); |
| 6217 | loop { |
| 6218 | let chunk = manager |
| 6219 | .read_output_chunk(&id, ShellOutputStream::Stdout, 0, 4096, 0) |
| 6220 | .unwrap(); |
| 6221 | if String::from_utf8_lossy(&chunk.bytes).contains("37 111") { |
| 6222 | break; |
| 6223 | } |
| 6224 | assert!( |
| 6225 | Instant::now() < deadline, |
| 6226 | "actual terminal size did not change" |
| 6227 | ); |
| 6228 | std::thread::sleep(Duration::from_millis(20)); |
| 6229 | } |
| 6230 | manager.kill(&id).unwrap(); |
| 6231 | assert!(manager.resize_pty(&id, size).is_err()); |
| 6232 | assert!(manager.processes[&id].pty_master.is_none()); |
| 6233 | let pipe = manager |
| 6234 | .execute_with_options_env( |
| 6235 | "cat", |
| 6236 | None, |
| 6237 | 5000, |
| 6238 | true, |
| 6239 | None, |
| 6240 | false, |
| 6241 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 6242 | HashMap::new(), |
| 6243 | ) |
| 6244 | .unwrap() |
| 6245 | .task_id |
| 6246 | .unwrap(); |
| 6247 | assert!(manager.resize_pty(&pipe, size).is_err()); |
| 6248 | manager.kill(&pipe).unwrap(); |
| 6249 | } |
| 6250 | |
| 6251 | #[test] |
| 6252 | #[cfg(all(unix, not(target_env = "ohos")))] |
| 6253 | fn pty_raw_stdin_roundtrips_nul_and_non_utf8_bytes() { |
| 6254 | let tmp = tempdir().unwrap(); |
| 6255 | let mut manager = ShellManager::new(tmp.path().to_path_buf()); |
| 6256 | let input = b"\0\xff\x1b[A\x03\n"; |
| 6257 | let command = format!( |
| 6258 | "stty raw -echo; printf ready; dd bs=1 count={} 2>/dev/null", |
| 6259 | input.len() |
| 6260 | ); |
| 6261 | let launched = manager |
| 6262 | .execute_with_options_env( |
| 6263 | &command, |
| 6264 | None, |
| 6265 | 5000, |
| 6266 | true, |
| 6267 | None, |
| 6268 | true, |
| 6269 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 6270 | HashMap::new(), |
| 6271 | ) |
| 6272 | .unwrap(); |
| 6273 | let id = launched.task_id.unwrap(); |
| 6274 | let deadline = Instant::now() + Duration::from_secs(5); |
| 6275 | loop { |
| 6276 | let chunk = manager |
| 6277 | .read_output_chunk(&id, ShellOutputStream::Stdout, 0, 4096, 0) |
| 6278 | .unwrap(); |
| 6279 | if chunk.bytes == b"ready" { |
| 6280 | break; |
| 6281 | } |
| 6282 | assert!(Instant::now() < deadline, "raw PTY did not become ready"); |
| 6283 | std::thread::sleep(Duration::from_millis(20)); |
| 6284 | } |
| 6285 | manager.write_stdin_bytes(&id, input, false).unwrap(); |
| 6286 | loop { |
| 6287 | let chunk = manager |
| 6288 | .read_output_chunk(&id, ShellOutputStream::Stdout, 5, 4096, 0) |
| 6289 | .unwrap(); |
| 6290 | if chunk.status != ShellStatus::Running { |
| 6291 | assert_eq!(chunk.bytes, input); |
| 6292 | assert_eq!(chunk.next_offset, 5 + input.len()); |
| 6293 | break; |
| 6294 | } |
| 6295 | assert!(Instant::now() < deadline, "raw PTY did not finish"); |
| 6296 | std::thread::sleep(Duration::from_millis(20)); |
| 6297 | } |
| 6298 | } |
| 6299 | |
| 6300 | /// #6654: a `Managed` background shell must (a) survive the exit of the thread |
| 6301 | /// that spawned it — callers such as `spawn_blocking` retire their threads — |
| 6302 | /// and (b) die with its whole process group when the TUI process is |
| 6303 | /// SIGKILLed, including a grandchild the shell did not `exec` (the shell |
| 6304 | /// itself keeps waiting on it). The TUI is played by a re-exec of this test |
| 6305 | /// binary. |
| 6306 | #[cfg(unix)] |
| 6307 | #[test] |
| 6308 | fn managed_background_shell_outlives_spawning_thread_but_not_the_tui() { |
| 6309 | const PROBE: &str = "CODEWHALE_TEST_BG_PDEATHSIG_PIDFILE"; |
| 6310 | |
| 6311 | #[cfg(target_os = "linux")] |
| 6312 | fn is_alive(pid: libc::pid_t) -> bool { |
| 6313 | // A killed child may linger as a zombie until its new parent reaps it |
| 6314 | // (a container's init may never do so). |
| 6315 | match std::fs::read_to_string(format!("/proc/{pid}/stat")) { |
| 6316 | Ok(stat) => stat |
| 6317 | .rsplit_once(')') |
| 6318 | .and_then(|(_, rest)| rest.split_whitespace().next()) |
| 6319 | .is_some_and(|state| state != "Z" && state != "X"), |
| 6320 | Err(_) => false, |
| 6321 | } |
| 6322 | } |
| 6323 | |
| 6324 | #[cfg(not(target_os = "linux"))] |
| 6325 | fn is_alive(pid: libc::pid_t) -> bool { |
| 6326 | // Orphans are reparented to launchd, which reaps them promptly. |
| 6327 | // SAFETY: kill(2) with signal 0 only checks for existence. |
| 6328 | unsafe { libc::kill(pid, 0) == 0 } |
| 6329 | } |
| 6330 | |
| 6331 | if let Some(pid_file) = std::env::var_os(PROBE) { |
| 6332 | // Probe role: spawn from a short-lived thread, let the thread exit, |
| 6333 | // mark readiness (libtest captures stdout, so through a file), then |
| 6334 | // hang until SIGKILLed. |
| 6335 | let pid_file = PathBuf::from(pid_file); |
| 6336 | let workspace = pid_file.parent().unwrap().to_path_buf(); |
| 6337 | // No `exec`: the shell forks `sleep` and waits, as `npm run dev; echo |
| 6338 | // done` or `a | b` would. |
| 6339 | let command = format!( |
| 6340 | "sleep 600 & echo \"$$ $!\" > '{}'; wait", |
| 6341 | pid_file.display() |
| 6342 | ); |
| 6343 | let manager = std::thread::spawn(move || { |
| 6344 | let mut manager = ShellManager::new(workspace); |
| 6345 | let result = manager |
| 6346 | .execute_with_options_env( |
| 6347 | &command, |
| 6348 | None, |
| 6349 | 600_000, |
| 6350 | true, |
| 6351 | None, |
| 6352 | false, |
| 6353 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 6354 | HashMap::new(), |
| 6355 | ) |
| 6356 | .expect("spawn background shell"); |
| 6357 | assert_eq!(result.status, ShellStatus::Running); |
| 6358 | manager |
| 6359 | }) |
| 6360 | .join() |
| 6361 | .expect("spawning thread"); |
| 6362 | std::fs::write(pid_file.with_extension("ready"), b"").expect("write ready marker"); |
| 6363 | let _keep_alive = manager; |
| 6364 | loop { |
| 6365 | std::thread::sleep(Duration::from_secs(60)); |
| 6366 | } |
| 6367 | } |
| 6368 | |
| 6369 | let tmp = tempdir().expect("tempdir"); |
| 6370 | let pid_file = tmp.path().join("bg.pid"); |
| 6371 | let ready_file = pid_file.with_extension("ready"); |
| 6372 | let mut tui = std::process::Command::new(std::env::current_exe().unwrap()) |
| 6373 | .args([ |
| 6374 | "--exact", |
| 6375 | "tools::shell::tests::managed_background_shell_outlives_spawning_thread_but_not_the_tui", |
| 6376 | "--test-threads=1", |
| 6377 | ]) |
| 6378 | .env(PROBE, &pid_file) |
| 6379 | .stdout(Stdio::null()) |
| 6380 | .stderr(Stdio::null()) |
| 6381 | .spawn() |
| 6382 | .expect("spawn probe process"); |
| 6383 | let deadline = Instant::now() + Duration::from_secs(30); |
| 6384 | let pids = loop { |
| 6385 | let pids = if ready_file.exists() { |
| 6386 | std::fs::read_to_string(&pid_file).ok().and_then(|text| { |
| 6387 | let pids = text |
| 6388 | .split_whitespace() |
| 6389 | .map(|pid| pid.parse::<libc::pid_t>().ok()) |
| 6390 | .collect::<Option<Vec<_>>>()?; |
| 6391 | (pids.len() == 2).then_some(pids) |
| 6392 | }) |
| 6393 | } else { |
| 6394 | None |
| 6395 | }; |
| 6396 | if let Some(pids) = pids { |
| 6397 | break pids; |
| 6398 | } |
| 6399 | if Instant::now() >= deadline || tui.try_wait().ok().flatten().is_some() { |
| 6400 | let _ = tui.kill(); |
| 6401 | let _ = tui.wait(); |
| 6402 | panic!("probe process never reported the background shell pid"); |
| 6403 | } |
| 6404 | std::thread::sleep(Duration::from_millis(20)); |
| 6405 | }; |
| 6406 | |
| 6407 | // The spawning thread is gone by now; give a mis-armed signal time to land. |
| 6408 | std::thread::sleep(Duration::from_millis(500)); |
| 6409 | let survived_thread_exit = pids.iter().all(|&pid| is_alive(pid)); |
| 6410 | |
| 6411 | tui.kill().expect("SIGKILL the probe process"); |
| 6412 | tui.wait().expect("reap the probe process"); |
| 6413 | let deadline = Instant::now() + Duration::from_secs(10); |
| 6414 | while pids.iter().any(|&pid| is_alive(pid)) && Instant::now() < deadline { |
| 6415 | std::thread::sleep(Duration::from_millis(20)); |
| 6416 | } |
| 6417 | let survivors = pids |
| 6418 | .iter() |
| 6419 | .copied() |
| 6420 | .filter(|&pid| is_alive(pid)) |
| 6421 | .collect::<Vec<_>>(); |
| 6422 | for &pid in &survivors { |
| 6423 | // SAFETY: plain kill(2) on a pid this test started. |
| 6424 | unsafe { |
| 6425 | libc::kill(pid, libc::SIGKILL); |
| 6426 | } |
| 6427 | } |
| 6428 | |
| 6429 | assert!( |
| 6430 | survived_thread_exit, |
| 6431 | "the background shell died when its spawning thread exited" |
| 6432 | ); |
| 6433 | assert!( |
| 6434 | survivors.is_empty(), |
| 6435 | "background processes outlived the SIGKILLed TUI: {survivors:?} of shell/grandchild {pids:?}" |
| 6436 | ); |
| 6437 | } |
| 6438 | |
| 6439 | #[tokio::test] |
| 6440 | async fn a_foreground_command_past_its_wait_moves_to_the_background_alive() { |
| 6441 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 6442 | let ctx = ToolContext::new(tmp.path()); |
| 6443 | let result = BashTool::new("Bash") |
| 6444 | .execute( |
| 6445 | json!({"command": "echo started; sleep 3; echo finished", "timeout_ms": 1_000}), |
| 6446 | &ctx, |
| 6447 | ) |
| 6448 | .await |
| 6449 | .expect("bash"); |
| 6450 | assert!(result.success, "{}", result.content); |
| 6451 | assert!(result.content.contains("not killed"), "{}", result.content); |
| 6452 | let metadata = result.metadata.as_ref().expect("metadata"); |
| 6453 | assert_eq!(metadata["status"], "Running"); |
| 6454 | assert_eq!(metadata["backgrounded"], true); |
| 6455 | let task_id = metadata["task_id"].as_str().expect("task_id").to_string(); |
| 6456 | let mut manager = ctx.shell_manager.lock().expect("shell manager lock"); |
| 6457 | assert!(manager.processes.get(&task_id).expect("tracked").background); |
| 6458 | let completed = wait_for_completed_shell(&mut manager, &task_id); |
| 6459 | assert_eq!(completed.status, ShellStatus::Completed); |
| 6460 | assert!(completed.stdout.contains("started"), "{completed:?}"); |
| 6461 | assert!(completed.stdout.contains("finished"), "{completed:?}"); |
| 6462 | } |
| 6463 | |
| 6464 | #[test] |
| 6465 | fn a_tool_launcher_clamps_a_danger_full_access_escalation() { |
| 6466 | let tmp = tempdir().expect("tempdir"); |
| 6467 | let ctx = ToolContext::new(tmp.path()); |
| 6468 | let escalation = json!({ |
| 6469 | "command": "id", |
| 6470 | "sandbox_permissions": "danger-full-access", |
| 6471 | "justification": "needs the host", |
| 6472 | }); |
| 6473 | let tool = BashTool::new("bash"); |
| 6474 | assert!(tool.refusal_before_approval(&escalation, &ctx).is_none()); |
| 6475 | |
| 6476 | ctx.shell_manager |
| 6477 | .lock() |
| 6478 | .unwrap() |
| 6479 | .set_tool_launcher(Some(vec!["/usr/bin/env".to_string()])); |
| 6480 | let refusal = tool |
| 6481 | .refusal_before_approval(&escalation, &ctx) |
| 6482 | .expect("escalation refused before approval"); |
| 6483 | assert!(!refusal.success); |
| 6484 | assert!( |
| 6485 | refusal.content.contains("danger-full-access"), |
| 6486 | "{}", |
| 6487 | refusal.content |
| 6488 | ); |
| 6489 | |
| 6490 | let error = ctx |
| 6491 | .shell_manager |
| 6492 | .lock() |
| 6493 | .unwrap() |
| 6494 | .execute_with_options_env( |
| 6495 | "id", |
| 6496 | Some(&tmp.path().to_string_lossy()), |
| 6497 | 1_000, |
| 6498 | false, |
| 6499 | None, |
| 6500 | false, |
| 6501 | Some(ExecutionSandboxPolicy::DangerFullAccess), |
| 6502 | HashMap::new(), |
| 6503 | ) |
| 6504 | .expect_err("an approved escalation still never runs unwrapped"); |
| 6505 | assert!( |
| 6506 | format!("{error:#}").contains("nothing was run"), |
| 6507 | "{error:#}" |
| 6508 | ); |
| 6509 | } |
| 6510 | |
| 6511 | #[cfg(unix)] |
| 6512 | #[tokio::test] |
| 6513 | async fn every_model_run_shell_command_carries_the_agent_project() { |
| 6514 | let workspace = tempdir().expect("workspace"); |
| 6515 | let project = workspace.path().to_string_lossy().into_owned(); |
| 6516 | let command = "printf '%s' \"${CODEWHALE_AGENT_PROJECT-unset}\""; |
| 6517 | let mut sandboxed = ToolContext::new(workspace.path()); |
| 6518 | sandboxed.auto_approve = true; |
| 6519 | let mut full_access = ToolContext::new(workspace.path()) |
| 6520 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::DangerFullAccess); |
| 6521 | full_access.auto_approve = true; |
| 6522 | for context in [&sandboxed, &full_access] { |
| 6523 | for tool in [BashTool::new("exec_shell"), BashTool::new("Bash")] { |
| 6524 | let result = tool |
| 6525 | .execute(json!({ "command": command }), context) |
| 6526 | .await |
| 6527 | .expect("shell runs"); |
| 6528 | assert_eq!(result.content.trim(), project, "{result:?}"); |
| 6529 | } |
| 6530 | let result = LowercaseBashTool |
| 6531 | .execute(json!({ "command": command }), context) |
| 6532 | .await |
| 6533 | .expect("bash runs"); |
| 6534 | assert_eq!(result.content.trim(), project, "{result:?}"); |
| 6535 | } |
| 6536 | } |
| 6537 | |
| 6538 | #[cfg(unix)] |
| 6539 | #[tokio::test] |
| 6540 | async fn persistent_terminal_commands_carry_the_agent_project() { |
| 6541 | use crate::tools::terminal_session::{TerminalResetTool, TerminalRunTool, TerminalSendTool}; |
| 6542 | let workspace = tempdir().expect("workspace"); |
| 6543 | let marked = format!("MARK={}", workspace.path().display()); |
| 6544 | let mut context = ToolContext::new(workspace.path()) |
| 6545 | .with_elevated_sandbox_policy(ExecutionSandboxPolicy::DangerFullAccess); |
| 6546 | context.auto_approve = true; |
| 6547 | let session = format!("agent-mark-{}", uuid::Uuid::new_v4().simple()); |
| 6548 | let print = "printf 'MARK=%s\\n' \"${CODEWHALE_AGENT_PROJECT-unset}\""; |
| 6549 | |
| 6550 | let run = TerminalRunTool |
| 6551 | .execute( |
| 6552 | json!({ "command": print, "session": session, "timeout_secs": 30 }), |
| 6553 | &context, |
| 6554 | ) |
| 6555 | .await |
| 6556 | .expect("terminal_run"); |
| 6557 | assert!(run.content.contains(&marked), "{}", run.content); |
| 6558 | |
| 6559 | let sent = TerminalSendTool |
| 6560 | .execute( |
| 6561 | json!({ "session": session, "text": format!("{print}\n"), "wait_ms": 2000 }), |
| 6562 | &context, |
| 6563 | ) |
| 6564 | .await |
| 6565 | .expect("terminal_send"); |
| 6566 | assert!(sent.content.contains(&marked), "{}", sent.content); |
| 6567 | let _ = TerminalResetTool |
| 6568 | .execute(json!({ "session": session }), &context) |
| 6569 | .await; |
| 6570 | } |
| 6571 | |
| 6572 | #[test] |
| 6573 | fn lowercase_bash_contract_translates_description_cwd_and_background() { |
| 6574 | let translated = super::contract_bash_legacy_input(&json!({ |
| 6575 | "command": "cargo test", |
| 6576 | "description": " run unit tests ", |
| 6577 | "cwd": "crates/engine", |
| 6578 | "background": true, |
| 6579 | })) |
| 6580 | .expect("valid bash input"); |
| 6581 | assert_eq!(translated["command"], "cargo test"); |
| 6582 | assert_eq!(translated["description"], "run unit tests"); |
| 6583 | assert_eq!(translated["cwd"], "crates/engine"); |
| 6584 | assert_eq!(translated["background"], true); |
| 6585 | |
| 6586 | let blank_desc = super::contract_bash_legacy_input(&json!({ |
| 6587 | "command": "pwd", |
| 6588 | "description": " \t\n ", |
| 6589 | })) |
| 6590 | .expect("blank description drops cleanly"); |
| 6591 | assert!(blank_desc.get("description").is_none()); |
| 6592 | |
| 6593 | let readonly_bg_false = super::contract_bash_legacy_input(&json!({ |
| 6594 | "command": "pwd", |
| 6595 | "description": "check dir", |
| 6596 | "read_only": true, |
| 6597 | "background": false, |
| 6598 | })) |
| 6599 | .expect("read_only with background=false translates"); |
| 6600 | assert_eq!(readonly_bg_false["background"], false); |
| 6601 | assert_eq!(readonly_bg_false["description"], "check dir"); |
| 6602 | |
| 6603 | for invalid in [ |
| 6604 | json!({"command": "pwd", "cwd": 123}), |
| 6605 | json!({"command": "pwd", "description": 42}), |
| 6606 | json!({"command": "pwd", "background": "true"}), |
| 6607 | json!({"command": "pwd", "background": null}), |
| 6608 | json!({"command": "sleep 5", "read_only": true, "background": true}), |
| 6609 | ] { |
| 6610 | assert!( |
| 6611 | super::contract_bash_legacy_input(&invalid).is_err(), |
| 6612 | "expected invalid input for {invalid}" |
| 6613 | ); |
| 6614 | } |
| 6615 | |
| 6616 | assert!(LowercaseBashTool.supports_parallel_for(&json!({ |
| 6617 | "command": "cargo test", |
| 6618 | "background": true, |
| 6619 | }))); |
| 6620 | assert!(LowercaseBashTool.starts_detached_for(&json!({ |
| 6621 | "command": "cargo test", |
| 6622 | "background": true, |
| 6623 | }))); |
| 6624 | assert!(!LowercaseBashTool.is_read_only_for(&json!({ |
| 6625 | "command": "cargo test", |
| 6626 | "background": true, |
| 6627 | }))); |
| 6628 | assert!(LowercaseBashTool.is_read_only_for(&json!({ |
| 6629 | "command": "git status -s", |
| 6630 | "description": "git status", |
| 6631 | }))); |
| 6632 | assert!(LowercaseBashTool.supports_parallel_for(&json!({ |
| 6633 | "command": "git status -s", |
| 6634 | "description": "git status", |
| 6635 | }))); |
| 6636 | assert!(!LowercaseBashTool.supports_parallel_for(&json!({ |
| 6637 | "command": "sleep 5", |
| 6638 | "read_only": true, |
| 6639 | "background": true, |
| 6640 | }))); |
| 6641 | assert!(!LowercaseBashTool.is_read_only_for(&json!({ |
| 6642 | "command": "sleep 5", |
| 6643 | "read_only": true, |
| 6644 | "background": true, |
| 6645 | }))); |
| 6646 | |
| 6647 | let workspace = tempdir().expect("workspace"); |
| 6648 | let ctx = ToolContext::new(workspace.path()); |
| 6649 | assert!( |
| 6650 | LowercaseBashTool |
| 6651 | .refusal_before_approval( |
| 6652 | &json!({"command": "rm -rf /", "read_only": true, "background": true}), |
| 6653 | &ctx, |
| 6654 | ) |
| 6655 | .is_some() |
| 6656 | ); |
| 6657 | assert!( |
| 6658 | LowercaseBashTool |
| 6659 | .refusal_before_approval( |
| 6660 | &json!({"command": "sleep 5", "read_only": true, "background": true}), |
| 6661 | &ctx, |
| 6662 | ) |
| 6663 | .is_none() |
| 6664 | ); |
| 6665 | } |
| 6666 | |
| 6667 | #[cfg(unix)] |
| 6668 | #[tokio::test] |
| 6669 | async fn lowercase_bash_persists_description_respects_cwd_and_supports_background() { |
| 6670 | let workspace = tempdir().expect("workspace"); |
| 6671 | let subdir = workspace.path().join("sub"); |
| 6672 | std::fs::create_dir_all(&subdir).expect("create subdir"); |
| 6673 | let mut ctx = ToolContext::new(workspace.path()); |
| 6674 | ctx.auto_approve = true; |
| 6675 | |
| 6676 | let fg = LowercaseBashTool |
| 6677 | .execute( |
| 6678 | json!({ |
| 6679 | "command": "pwd", |
| 6680 | "cwd": "sub", |
| 6681 | "description": " print subdir ", |
| 6682 | }), |
| 6683 | &ctx, |
| 6684 | ) |
| 6685 | .await |
| 6686 | .expect("foreground bash in cwd"); |
| 6687 | assert_eq!( |
| 6688 | fg.content.trim(), |
| 6689 | subdir.canonicalize().unwrap().to_string_lossy() |
| 6690 | ); |
| 6691 | assert_eq!(fg.metadata.as_ref().unwrap()["description"], "print subdir"); |
| 6692 | |
| 6693 | let escaped = LowercaseBashTool |
| 6694 | .execute( |
| 6695 | json!({ |
| 6696 | "command": "pwd", |
| 6697 | "cwd": "../outside", |
| 6698 | }), |
| 6699 | &ctx, |
| 6700 | ) |
| 6701 | .await |
| 6702 | .expect_err("cwd outside workspace must fail"); |
| 6703 | assert!( |
| 6704 | escaped.to_string().contains("outside") || escaped.to_string().contains("workspace"), |
| 6705 | "{escaped}" |
| 6706 | ); |
| 6707 | |
| 6708 | let bg = LowercaseBashTool |
| 6709 | .execute( |
| 6710 | json!({ |
| 6711 | "command": sleep_command(30), |
| 6712 | "cwd": "sub", |
| 6713 | "background": true, |
| 6714 | "description": " background sleeper ", |
| 6715 | }), |
| 6716 | &ctx, |
| 6717 | ) |
| 6718 | .await |
| 6719 | .expect("background bash start"); |
| 6720 | let bg_meta = bg.metadata.expect("background metadata"); |
| 6721 | assert_eq!(bg_meta["status"], "Running"); |
| 6722 | assert_eq!(bg_meta["backgrounded"], true); |
| 6723 | assert_eq!(bg_meta["description"], "background sleeper"); |
| 6724 | let task_id = bg_meta["task_id"].as_str().expect("task_id"); |
| 6725 | |
| 6726 | { |
| 6727 | let mut manager = ctx.shell_manager.lock().expect("shell manager lock"); |
| 6728 | let detail = manager.inspect_job(task_id).expect("inspect bg job"); |
| 6729 | assert_eq!( |
| 6730 | detail.snapshot.description.as_deref(), |
| 6731 | Some("background sleeper") |
| 6732 | ); |
| 6733 | assert_eq!(detail.snapshot.cwd, subdir.canonicalize().unwrap()); |
| 6734 | let serialized = serde_json::to_value(&detail.snapshot).expect("serialize snapshot"); |
| 6735 | assert_eq!(serialized["description"], "background sleeper"); |
| 6736 | manager.kill(task_id).expect("kill bg job"); |
| 6737 | } |
| 6738 | |
| 6739 | let bash_tool = BashTool::new("Bash"); |
| 6740 | assert_eq!( |
| 6741 | bash_tool.input_schema()["properties"]["description"]["type"], |
| 6742 | "string" |
| 6743 | ); |
| 6744 | let legacy = bash_tool |
| 6745 | .execute( |
| 6746 | json!({ |
| 6747 | "action": "run", |
| 6748 | "command": "printf ok", |
| 6749 | "description": " legacy run label ", |
| 6750 | }), |
| 6751 | &ctx, |
| 6752 | ) |
| 6753 | .await |
| 6754 | .expect("BashTool action=run with description"); |
| 6755 | assert_eq!(legacy.content, "ok"); |
| 6756 | assert_eq!( |
| 6757 | legacy.metadata.as_ref().unwrap()["description"], |
| 6758 | "legacy run label" |
| 6759 | ); |
| 6760 | } |
| 6761 | |
| 6762 | #[cfg(unix)] |
| 6763 | #[tokio::test] |
| 6764 | #[allow(clippy::await_holding_lock)] |
| 6765 | async fn foreground_bash_large_output_persists_session_artifact_readable_via_retrieve_tool_result() |
| 6766 | { |
| 6767 | use crate::tools::tool_result_retrieval::RetrieveToolResultTool; |
| 6768 | |
| 6769 | let _artifact_lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD |
| 6770 | .lock() |
| 6771 | .unwrap_or_else(|error| error.into_inner()); |
| 6772 | struct ArtifactRootReset(Option<PathBuf>); |
| 6773 | impl Drop for ArtifactRootReset { |
| 6774 | fn drop(&mut self) { |
| 6775 | codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take()); |
| 6776 | } |
| 6777 | } |
| 6778 | |
| 6779 | let workspace = tempdir().expect("workspace"); |
| 6780 | let _artifact_root = ArtifactRootReset( |
| 6781 | codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some( |
| 6782 | workspace.path().join("sessions"), |
| 6783 | )), |
| 6784 | ); |
| 6785 | |
| 6786 | let base_ctx = ToolContext::new(workspace.path()).with_state_namespace("session-fg-art"); |
| 6787 | assert!(!base_ctx.trust_mode); |
| 6788 | assert!(!base_ctx.auto_approve); |
| 6789 | |
| 6790 | let ctx_lowercase = base_ctx.clone().with_origin_tool_call_id("call-fg-large-1"); |
| 6791 | let preview = codewhale_runtime::artifacts::write_session_artifact_immutable( |
| 6792 | "session-fg-art", |
| 6793 | "art_call-fg-large-1", |
| 6794 | b"still running", |
| 6795 | ) |
| 6796 | .expect("store provisional output"); |
| 6797 | let lowercase_cmd = "printf 'START_MARKER_0\\n'; i=1; while [ $i -le 1100 ]; do printf 'pad-a-%04d-xxxxxxxxxxxxxxxxxxxxxxxxxxxx\\n' \"$i\"; i=$((i+1)); done; printf 'MID_MARKER_PAST_30KB\\n'; while [ $i -le 2200 ]; do printf 'pad-b-%04d-yyyyyyyyyyyyyyyyyyyyyyyyyyyy\\n' \"$i\"; i=$((i+1)); done; printf 'END_MARKER_TAIL\\n'"; |
| 6798 | let lowercase_result = LowercaseBashTool |
| 6799 | .execute(json!({"command": lowercase_cmd}), &ctx_lowercase) |
| 6800 | .await |
| 6801 | .expect("large foreground bash"); |
| 6802 | assert!(lowercase_result.success, "{}", lowercase_result.content); |
| 6803 | assert!(lowercase_result.content.contains("END_MARKER_TAIL")); |
| 6804 | assert!(!lowercase_result.content.contains("START_MARKER_0")); |
| 6805 | assert!(!lowercase_result.content.contains("codewhale-bash-")); |
| 6806 | assert!(!lowercase_result.content.contains("/var/folders/")); |
| 6807 | assert!(lowercase_result.content.contains("retrieve_tool_result")); |
| 6808 | assert!(lowercase_result.content.len() < 60_000); |
| 6809 | let lc_meta = lowercase_result.metadata.expect("lowercase metadata"); |
| 6810 | let final_id = lc_meta["artifact_id"].as_str().expect("completed artifact"); |
| 6811 | assert_ne!(final_id, "art_call-fg-large-1"); |
| 6812 | assert!(lowercase_result.content.contains(final_id)); |
| 6813 | assert_eq!(std::fs::read(preview.0).unwrap(), b"still running"); |
| 6814 | assert_eq!(lc_meta["artifact_session_id"], "session-fg-art"); |
| 6815 | assert_eq!(lc_meta["truncated"], true); |
| 6816 | assert!( |
| 6817 | lc_meta["original_byte_count"] |
| 6818 | .as_u64() |
| 6819 | .expect("original byte count") |
| 6820 | > 60_000 |
| 6821 | ); |
| 6822 | |
| 6823 | for marker in ["START_MARKER_0", "MID_MARKER_PAST_30KB", "END_MARKER_TAIL"] { |
| 6824 | let retrieved = RetrieveToolResultTool |
| 6825 | .execute( |
| 6826 | json!({ |
| 6827 | "ref": final_id, |
| 6828 | "mode": "query", |
| 6829 | "query": marker, |
| 6830 | }), |
| 6831 | &base_ctx, |
| 6832 | ) |
| 6833 | .await |
| 6834 | .expect("retrieve foreground bash artifact"); |
| 6835 | assert!( |
| 6836 | retrieved.content.contains(marker), |
| 6837 | "expected {marker} in retrieved output: {}", |
| 6838 | retrieved.content |
| 6839 | ); |
| 6840 | } |
| 6841 | |
| 6842 | let ctx_bash = base_ctx.clone().with_origin_tool_call_id("call-fg-large-2"); |
| 6843 | let bash_cmd = "printf 'BASH_START_MARKER\\n'; i=1; while [ $i -le 700 ]; do printf 'row-%04d-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\\n' \"$i\"; i=$((i+1)); done; printf 'BASH_MID_PAST_30KB\\n'; while [ $i -le 1400 ]; do printf 'row-%04d-wwwwwwwwwwwwwwwwwwwwwwwwwwwwww\\n' \"$i\"; i=$((i+1)); done; printf 'BASH_END_MARKER\\n'"; |
| 6844 | let bash_result = BashTool::new("Bash") |
| 6845 | .execute(json!({"command": bash_cmd}), &ctx_bash) |
| 6846 | .await |
| 6847 | .expect("large foreground BashTool"); |
| 6848 | assert!(bash_result.success, "{}", bash_result.content); |
| 6849 | assert!(bash_result.content.contains("BASH_START_MARKER")); |
| 6850 | assert!(bash_result.content.contains("BASH_END_MARKER")); |
| 6851 | assert!(!bash_result.content.contains("BASH_MID_PAST_30KB")); |
| 6852 | assert!(bash_result.content.contains("art_call-fg-large-2")); |
| 6853 | assert!(bash_result.content.contains("retrieve_tool_result")); |
| 6854 | let bash_meta = bash_result.metadata.expect("bash metadata"); |
| 6855 | assert_eq!(bash_meta["artifact_id"], "art_call-fg-large-2"); |
| 6856 | assert!( |
| 6857 | bash_meta["original_byte_count"] |
| 6858 | .as_u64() |
| 6859 | .expect("original byte count") |
| 6860 | > 50_000 |
| 6861 | ); |
| 6862 | |
| 6863 | let mid = RetrieveToolResultTool |
| 6864 | .execute( |
| 6865 | json!({ |
| 6866 | "ref": "art_call-fg-large-2", |
| 6867 | "mode": "query", |
| 6868 | "query": "BASH_MID_PAST_30KB", |
| 6869 | }), |
| 6870 | &base_ctx, |
| 6871 | ) |
| 6872 | .await |
| 6873 | .expect("retrieve BashTool omitted middle"); |
| 6874 | assert!( |
| 6875 | mid.content.contains("BASH_MID_PAST_30KB"), |
| 6876 | "{}", |
| 6877 | mid.content |
| 6878 | ); |
| 6879 | |
| 6880 | let mut payload = b"RAW_START\n".to_vec(); |
| 6881 | payload.resize(21 * 1024 * 1024, b'x'); |
| 6882 | payload.extend_from_slice(b"\nRAW_END\n"); |
| 6883 | std::fs::write(workspace.path().join("large.bin"), &payload).unwrap(); |
| 6884 | let raw = BashTool::new("Bash") |
| 6885 | .execute( |
| 6886 | json!({"command": "cat large.bin; printf 'stderr-end' >&2"}), |
| 6887 | &base_ctx.clone().with_origin_tool_call_id("raw-over-cap"), |
| 6888 | ) |
| 6889 | .await |
| 6890 | .unwrap(); |
| 6891 | assert!(raw.success, "{}", raw.content); |
| 6892 | let metadata = raw.metadata.unwrap(); |
| 6893 | assert_eq!(metadata["artifact_complete"], true); |
| 6894 | payload.extend_from_slice(b"\n\nSTDERR:\nstderr-end"); |
| 6895 | let bytes = std::fs::read(metadata["artifact_path"].as_str().unwrap()).unwrap(); |
| 6896 | assert_eq!(bytes.len(), payload.len()); |
| 6897 | assert!(bytes == payload); |
| 6898 | assert_eq!(metadata["original_byte_count"], payload.len() as u64); |
| 6899 | |
| 6900 | let ctx_fail = base_ctx.clone().with_origin_tool_call_id("call-fg-large-3"); |
| 6901 | let fail_err = LowercaseBashTool |
| 6902 | .execute( |
| 6903 | json!({"command": format!("{lowercase_cmd}; exit 2")}), |
| 6904 | &ctx_fail, |
| 6905 | ) |
| 6906 | .await |
| 6907 | .expect_err("nonzero foreground bash returns error"); |
| 6908 | let fail_text = fail_err.to_string(); |
| 6909 | assert!(fail_text.contains("retrieve_tool_result"), "{fail_text}"); |
| 6910 | assert!(!fail_text.contains("codewhale-bash-"), "{fail_text}"); |
| 6911 | let failure_id = fail_err.metadata().expect("fail metadata")["artifact_id"] |
| 6912 | .as_str() |
| 6913 | .expect("failed command artifact"); |
| 6914 | assert!(fail_text.contains(failure_id), "{fail_text}"); |
| 6915 | let fail_retrieved = RetrieveToolResultTool |
| 6916 | .execute( |
| 6917 | json!({ |
| 6918 | "ref": failure_id, |
| 6919 | "mode": "query", |
| 6920 | "query": "MID_MARKER_PAST_30KB", |
| 6921 | }), |
| 6922 | &base_ctx, |
| 6923 | ) |
| 6924 | .await |
| 6925 | .expect("retrieve failing bash artifact"); |
| 6926 | assert!(fail_retrieved.content.contains("MID_MARKER_PAST_30KB")); |
| 6927 | } |
| 6928 | |
| 6929 | #[test] |
| 6930 | fn bounded_spill_finalization_retries_before_acknowledging_wait_or_completion() { |
| 6931 | let _lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD |
| 6932 | .lock() |
| 6933 | .unwrap_or_else(|error| error.into_inner()); |
| 6934 | struct ResetRoot(Option<std::path::PathBuf>); |
| 6935 | impl Drop for ResetRoot { |
| 6936 | fn drop(&mut self) { |
| 6937 | codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take()); |
| 6938 | } |
| 6939 | } |
| 6940 | let fixture = tempdir().unwrap(); |
| 6941 | let sessions = fixture.path().join("sessions"); |
| 6942 | let _root = ResetRoot( |
| 6943 | codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(sessions.clone())), |
| 6944 | ); |
| 6945 | for wait in [true, false] { |
| 6946 | let session = if wait { |
| 6947 | "wait-session" |
| 6948 | } else { |
| 6949 | "drain-session" |
| 6950 | }; |
| 6951 | let mut manager = ShellManager::new(fixture.path().to_path_buf()); |
| 6952 | manager.seed_finished_record_for_test("fixture-job", Duration::ZERO); |
| 6953 | let mut output = BoundedOutputAccumulator::new_in( |
| 6954 | Some(fixture.path()), |
| 6955 | Some(SessionArtifactSpec { |
| 6956 | session_id: session.into(), |
| 6957 | artifact_id: "art_fixture".into(), |
| 6958 | }), |
| 6959 | ); |
| 6960 | let chunk = [0xff; 4096]; |
| 6961 | for _ in 0..512 { |
| 6962 | output.append(&chunk).unwrap(); |
| 6963 | } |
| 6964 | let shell = manager.processes.get_mut("fixture-job").unwrap(); |
| 6965 | shell.owner_session_id = session.into(); |
| 6966 | shell.status = ShellStatus::Running; |
| 6967 | shell.bounded_output = Some(Arc::new(Mutex::new(output))); |
| 6968 | let running = shell.take_delta(); |
| 6969 | assert!(running.2 > 16 * 1024); |
| 6970 | assert!(running.6.is_none()); |
| 6971 | shell |
| 6972 | .bounded_output |
| 6973 | .as_ref() |
| 6974 | .unwrap() |
| 6975 | .lock() |
| 6976 | .unwrap() |
| 6977 | .finish() |
| 6978 | .unwrap(); |
| 6979 | shell.status = ShellStatus::Completed; |
| 6980 | std::fs::create_dir_all(sessions.join(session)).unwrap(); |
| 6981 | let blocked = sessions.join(session).join("artifacts"); |
| 6982 | std::fs::write(&blocked, b"fixture obstruction").unwrap(); |
| 6983 | let cursor = shell.stdout_cursor; |
| 6984 | if wait { |
| 6985 | assert!( |
| 6986 | manager |
| 6987 | .get_raw_output_delta("fixture-job", false, 0) |
| 6988 | .is_err() |
| 6989 | ); |
| 6990 | } else { |
| 6991 | assert!(manager.drain_finished_jobs_with_evidence().is_empty()); |
| 6992 | } |
| 6993 | let shell = &manager.processes["fixture-job"]; |
| 6994 | assert!(!shell.completion_reported); |
| 6995 | assert_eq!(shell.stdout_cursor, cursor); |
| 6996 | assert_eq!( |
| 6997 | shell |
| 6998 | .bounded_output |
| 6999 | .as_ref() |
| 7000 | .unwrap() |
| 7001 | .lock() |
| 7002 | .unwrap() |
| 7003 | .retained_raw_bytes() |
| 7004 | .unwrap() |
| 7005 | .0, |
| 7006 | vec![0xff; 16 * 1024] |
| 7007 | ); |
| 7008 | std::fs::remove_file(&blocked).unwrap(); |
| 7009 | let artifact = if wait { |
| 7010 | let result = manager |
| 7011 | .get_raw_output_delta("fixture-job", false, 0) |
| 7012 | .unwrap(); |
| 7013 | assert!(result.stdout.is_empty()); |
| 7014 | assert_eq!(result.stdout_delta_len, 0); |
| 7015 | result.persisted_artifact.unwrap() |
| 7016 | } else { |
| 7017 | let completions = manager.drain_finished_jobs_with_evidence(); |
| 7018 | assert_eq!(completions.len(), 1); |
| 7019 | let evidence = &completions[0]; |
| 7020 | assert!(evidence.stdout.len() <= 16 * 1024); |
| 7021 | assert!(evidence.artifact_bytes().len() < 32 * 1024); |
| 7022 | let payload: Value = serde_json::from_slice(&evidence.artifact_bytes()).unwrap(); |
| 7023 | assert_eq!(payload["stdout"]["artifact_id"], "art_fixture"); |
| 7024 | evidence.persisted_artifact.clone().unwrap() |
| 7025 | }; |
| 7026 | assert!(manager.processes["fixture-job"].completion_reported); |
| 7027 | let raw = vec![0xff; 2 * 1024 * 1024]; |
| 7028 | assert_eq!(std::fs::read(&artifact.absolute_path).unwrap(), raw); |
| 7029 | assert_eq!(artifact.byte_size, raw.len() as u64); |
| 7030 | assert_eq!( |
| 7031 | artifact.digest, |
| 7032 | codewhale_runtime::hashing::sha256_hex(&raw) |
| 7033 | ); |
| 7034 | } |
| 7035 | } |
| 7036 |