| 1 | #![cfg(unix)] |
| 2 | |
| 3 | use std::io::{BufRead, BufReader, Read, Write}; |
| 4 | use std::net::{SocketAddr, TcpListener, TcpStream}; |
| 5 | use std::path::Path; |
| 6 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 7 | use std::sync::{Arc, Mutex}; |
| 8 | use std::time::Duration; |
| 9 | |
| 10 | use serde_json::{Value, json}; |
| 11 | |
| 12 | use super::qa_harness; |
| 13 | use qa_harness::harness::{Harness, ci_scaled, make_sealed_workspace}; |
| 14 | |
| 15 | const MODEL: &str = "fixture-model"; |
| 16 | const SAFE_CMD: &str = "printf safe > safe-canary.txt"; |
| 17 | const DANGER_CMD: &str = "printf danger > danger-canary.txt"; |
| 18 | const RETRY_CMD: &str = "printf retried > retried-canary.txt"; |
| 19 | |
| 20 | const SAFE_PROMPT: &str = "Please run printf safe > safe-canary.txt"; |
| 21 | const DANGER_PROMPT: &str = "Inspect the directory without writing files"; |
| 22 | const RETRY_PROMPT: &str = "Please run printf retried > retried-canary.txt"; |
| 23 | const FOLLOWUP_PROMPT: &str = "Run the approved command again"; |
| 24 | |
| 25 | #[derive(Debug, Clone)] |
| 26 | struct GuardianRecord { |
| 27 | decision: String, |
| 28 | reason: String, |
| 29 | person_messages: Vec<String>, |
| 30 | person_approved_retry: bool, |
| 31 | proposed: String, |
| 32 | } |
| 33 | |
| 34 | struct MockProvider { |
| 35 | address: SocketAddr, |
| 36 | stop: Arc<AtomicBool>, |
| 37 | guardians: Arc<Mutex<Vec<GuardianRecord>>>, |
| 38 | acceptor: Option<std::thread::JoinHandle<()>>, |
| 39 | } |
| 40 | |
| 41 | impl MockProvider { |
| 42 | fn start() -> Self { |
| 43 | let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback provider"); |
| 44 | let address = listener.local_addr().expect("provider addr"); |
| 45 | let stop = Arc::new(AtomicBool::new(false)); |
| 46 | let guardians = Arc::new(Mutex::new(Vec::new())); |
| 47 | let stop_flag = Arc::clone(&stop); |
| 48 | let log = Arc::clone(&guardians); |
| 49 | let call_seq = Arc::new(AtomicUsize::new(1)); |
| 50 | let acceptor = std::thread::spawn(move || { |
| 51 | for stream in listener.incoming() { |
| 52 | if stop_flag.load(Ordering::Acquire) { |
| 53 | break; |
| 54 | } |
| 55 | let Ok(stream) = stream else { continue }; |
| 56 | let log = Arc::clone(&log); |
| 57 | let seq = Arc::clone(&call_seq); |
| 58 | std::thread::spawn(move || { |
| 59 | let _ = handle_connection(stream, &log, &seq); |
| 60 | }); |
| 61 | } |
| 62 | }); |
| 63 | Self { |
| 64 | address, |
| 65 | stop, |
| 66 | guardians, |
| 67 | acceptor: Some(acceptor), |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | fn base_url(&self) -> String { |
| 72 | format!("http://{}/v1", self.address) |
| 73 | } |
| 74 | |
| 75 | fn records(&self) -> Vec<GuardianRecord> { |
| 76 | self.guardians.lock().unwrap().clone() |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | impl Drop for MockProvider { |
| 81 | fn drop(&mut self) { |
| 82 | self.stop.store(true, Ordering::Release); |
| 83 | let _ = TcpStream::connect(self.address); |
| 84 | if let Some(acceptor) = self.acceptor.take() { |
| 85 | let _ = acceptor.join(); |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | fn text_of(content: &Value) -> String { |
| 91 | if let Some(items) = content.as_array() { |
| 92 | return items |
| 93 | .iter() |
| 94 | .filter_map(|item| item.get("text").and_then(Value::as_str)) |
| 95 | .collect::<Vec<_>>() |
| 96 | .join(" "); |
| 97 | } |
| 98 | content.as_str().unwrap_or_default().to_string() |
| 99 | } |
| 100 | |
| 101 | fn strip_turn_meta(text: &str) -> String { |
| 102 | let mut out = String::with_capacity(text.len()); |
| 103 | let mut rest = text; |
| 104 | while let Some(start) = rest.find("<turn_meta>") { |
| 105 | out.push_str(&rest[..start]); |
| 106 | if let Some(end) = rest[start..].find("</turn_meta>") { |
| 107 | rest = &rest[start + end + "</turn_meta>".len()..]; |
| 108 | } else { |
| 109 | rest = ""; |
| 110 | break; |
| 111 | } |
| 112 | } |
| 113 | out.push_str(rest); |
| 114 | out |
| 115 | } |
| 116 | |
| 117 | fn is_human_turn(msg: &Value) -> bool { |
| 118 | if msg.get("role").and_then(Value::as_str) != Some("user") { |
| 119 | return false; |
| 120 | } |
| 121 | let text = strip_turn_meta(&text_of(&msg["content"])); |
| 122 | let trimmed = text.trim_start(); |
| 123 | !trimmed.starts_with("<codewhale:runtime_event") |
| 124 | && !text.contains("\"current_deferred_toolbox\"") |
| 125 | && !text.contains("\"proposed_tool_call\"") |
| 126 | } |
| 127 | |
| 128 | fn extract_review_doc(messages: &[Value]) -> Option<Value> { |
| 129 | for msg in messages { |
| 130 | if msg.get("role").and_then(Value::as_str) != Some("user") { |
| 131 | continue; |
| 132 | } |
| 133 | let text = text_of(&msg["content"]); |
| 134 | let mut idx = 0usize; |
| 135 | while let Some(offset) = text[idx..].find('{') { |
| 136 | let start = idx + offset; |
| 137 | let mut de = serde_json::Deserializer::from_str(&text[start..]).into_iter::<Value>(); |
| 138 | if let Some(Ok(doc)) = de.next() |
| 139 | && doc.is_object() |
| 140 | && doc.get("person_messages").is_some() |
| 141 | { |
| 142 | return Some(doc); |
| 143 | } |
| 144 | idx = start + 1; |
| 145 | } |
| 146 | } |
| 147 | None |
| 148 | } |
| 149 | |
| 150 | fn judge_guardian(doc: &Value) -> (&'static str, &'static str, &'static str) { |
| 151 | let persons: Vec<String> = doc["person_messages"] |
| 152 | .as_array() |
| 153 | .map(|items| { |
| 154 | items |
| 155 | .iter() |
| 156 | .filter_map(Value::as_str) |
| 157 | .map(ToOwned::to_owned) |
| 158 | .collect() |
| 159 | }) |
| 160 | .unwrap_or_default(); |
| 161 | let proposed = serde_json::to_string(&doc["proposed_tool_call"]).unwrap_or_default(); |
| 162 | let approved_retry = |
| 163 | doc["deterministic_observations"]["person_approved_retry"].as_bool() == Some(true); |
| 164 | if persons.is_empty() { |
| 165 | return ( |
| 166 | "deny", |
| 167 | "high", |
| 168 | "No person request provided (person_messages is empty).", |
| 169 | ); |
| 170 | } |
| 171 | if proposed.contains("safe-canary.txt") && persons.iter().any(|p| p.contains("safe-canary.txt")) |
| 172 | { |
| 173 | return ( |
| 174 | "allow", |
| 175 | "low", |
| 176 | "Person explicitly requested creating safe-canary.txt.", |
| 177 | ); |
| 178 | } |
| 179 | if proposed.contains("danger-canary.txt") { |
| 180 | return ( |
| 181 | "deny", |
| 182 | "high", |
| 183 | "Unrequested dangerous write to danger-canary.txt blocked.", |
| 184 | ); |
| 185 | } |
| 186 | if proposed.contains("retried-canary.txt") { |
| 187 | if approved_retry { |
| 188 | return ( |
| 189 | "allow", |
| 190 | "low", |
| 191 | "Person approved one-time retry of this exact call.", |
| 192 | ); |
| 193 | } |
| 194 | return ( |
| 195 | "deny", |
| 196 | "high", |
| 197 | "Held write awaiting explicit person retry approval.", |
| 198 | ); |
| 199 | } |
| 200 | ("deny", "medium", "Unrecognized command blocked.") |
| 201 | } |
| 202 | |
| 203 | fn handle_connection( |
| 204 | mut stream: TcpStream, |
| 205 | guardians: &Mutex<Vec<GuardianRecord>>, |
| 206 | call_seq: &AtomicUsize, |
| 207 | ) -> std::io::Result<()> { |
| 208 | stream.set_read_timeout(Some(Duration::from_secs(10)))?; |
| 209 | let mut reader = BufReader::new(stream.try_clone()?); |
| 210 | let mut request_line = String::new(); |
| 211 | if reader.read_line(&mut request_line)? == 0 { |
| 212 | return Ok(()); |
| 213 | } |
| 214 | let mut content_length = 0usize; |
| 215 | loop { |
| 216 | let mut header = String::new(); |
| 217 | if reader.read_line(&mut header)? == 0 { |
| 218 | break; |
| 219 | } |
| 220 | let header = header.trim_end(); |
| 221 | if header.is_empty() { |
| 222 | break; |
| 223 | } |
| 224 | if let Some((name, value)) = header.split_once(':') |
| 225 | && name.eq_ignore_ascii_case("content-length") |
| 226 | { |
| 227 | content_length = value.trim().parse().unwrap_or(0); |
| 228 | } |
| 229 | } |
| 230 | let mut body = vec![0u8; content_length.min(8 * 1024 * 1024)]; |
| 231 | reader.read_exact(&mut body)?; |
| 232 | let mut parts = request_line.split_whitespace(); |
| 233 | let method = parts.next().unwrap_or_default(); |
| 234 | let path = parts.next().unwrap_or_default(); |
| 235 | if method == "GET" && path.ends_with("/models") { |
| 236 | return write_json( |
| 237 | &mut stream, |
| 238 | "200 OK", |
| 239 | &json!({"object": "list", "data": [{"id": MODEL, "object": "model"}]}), |
| 240 | ); |
| 241 | } |
| 242 | if method != "POST" { |
| 243 | return write_json(&mut stream, "404 Not Found", &json!({"error": "not found"})); |
| 244 | } |
| 245 | |
| 246 | let request: Value = serde_json::from_slice(&body).unwrap_or_default(); |
| 247 | let messages = request["messages"].as_array().cloned().unwrap_or_default(); |
| 248 | let system_text = messages |
| 249 | .iter() |
| 250 | .filter(|m| m.get("role").and_then(Value::as_str) == Some("system")) |
| 251 | .map(|m| text_of(&m["content"]).to_ascii_lowercase()) |
| 252 | .collect::<Vec<_>>() |
| 253 | .join(" "); |
| 254 | |
| 255 | if system_text.contains("auto-review guardian") { |
| 256 | let doc = extract_review_doc(&messages).unwrap_or_else(|| json!({})); |
| 257 | let (decision, risk, reason) = judge_guardian(&doc); |
| 258 | let person_messages: Vec<String> = doc["person_messages"] |
| 259 | .as_array() |
| 260 | .map(|items| { |
| 261 | items |
| 262 | .iter() |
| 263 | .filter_map(Value::as_str) |
| 264 | .map(ToOwned::to_owned) |
| 265 | .collect() |
| 266 | }) |
| 267 | .unwrap_or_default(); |
| 268 | let person_approved_retry = |
| 269 | doc["deterministic_observations"]["person_approved_retry"].as_bool() == Some(true); |
| 270 | let proposed = serde_json::to_string(&doc["proposed_tool_call"]).unwrap_or_default(); |
| 271 | guardians.lock().unwrap().push(GuardianRecord { |
| 272 | decision: decision.to_string(), |
| 273 | reason: reason.to_string(), |
| 274 | person_messages, |
| 275 | person_approved_retry, |
| 276 | proposed, |
| 277 | }); |
| 278 | let content = json!({ |
| 279 | "risk_level": risk, |
| 280 | "decision": decision, |
| 281 | "reason": reason, |
| 282 | }) |
| 283 | .to_string(); |
| 284 | return write_json( |
| 285 | &mut stream, |
| 286 | "200 OK", |
| 287 | &json!({ |
| 288 | "id": "guardian", |
| 289 | "object": "chat.completion", |
| 290 | "model": MODEL, |
| 291 | "choices": [{"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop"}], |
| 292 | "usage": {"prompt_tokens": 20, "completion_tokens": 40, "total_tokens": 60}, |
| 293 | }), |
| 294 | ); |
| 295 | } |
| 296 | |
| 297 | let bash_name = request["tools"].as_array().and_then(|tools| { |
| 298 | tools.iter().find_map(|tool| { |
| 299 | let name = tool["function"]["name"].as_str()?; |
| 300 | name.eq_ignore_ascii_case("bash").then(|| name.to_string()) |
| 301 | }) |
| 302 | }); |
| 303 | let last_user_idx = messages |
| 304 | .iter() |
| 305 | .rposition(|m| { |
| 306 | if !is_human_turn(m) { |
| 307 | return false; |
| 308 | } |
| 309 | let t = strip_turn_meta(&text_of(&m["content"])); |
| 310 | t.contains(SAFE_PROMPT) |
| 311 | || t.contains(DANGER_PROMPT) |
| 312 | || t.contains(RETRY_PROMPT) |
| 313 | || t.contains(FOLLOWUP_PROMPT) |
| 314 | }) |
| 315 | .or_else(|| messages.iter().rposition(is_human_turn)); |
| 316 | let prompt_text = last_user_idx |
| 317 | .map(|idx| strip_turn_meta(&text_of(&messages[idx]["content"]))) |
| 318 | .unwrap_or_default(); |
| 319 | let already_called = last_user_idx.is_some_and(|idx| { |
| 320 | messages[idx + 1..].iter().any(|m| { |
| 321 | m.get("role").and_then(Value::as_str) == Some("assistant") |
| 322 | && m.get("tool_calls").is_some() |
| 323 | }) |
| 324 | }); |
| 325 | |
| 326 | let command_to_run = if prompt_text.contains(SAFE_PROMPT) { |
| 327 | Some(SAFE_CMD) |
| 328 | } else if prompt_text.contains(DANGER_PROMPT) { |
| 329 | Some(DANGER_CMD) |
| 330 | } else if prompt_text.contains(RETRY_PROMPT) || prompt_text.contains(FOLLOWUP_PROMPT) { |
| 331 | Some(RETRY_CMD) |
| 332 | } else { |
| 333 | None |
| 334 | }; |
| 335 | |
| 336 | let tool_call = match (command_to_run, already_called, bash_name) { |
| 337 | (Some(cmd), false, Some(tool_name)) => { |
| 338 | let id = format!("call_ar_{}", call_seq.fetch_add(1, Ordering::AcqRel)); |
| 339 | Some((id, tool_name, json!({ "command": cmd }).to_string())) |
| 340 | } |
| 341 | _ => None, |
| 342 | }; |
| 343 | |
| 344 | if !request["stream"].as_bool().unwrap_or(false) { |
| 345 | let message = match tool_call { |
| 346 | Some((id, name, arguments)) => json!({ |
| 347 | "role": "assistant", |
| 348 | "content": null, |
| 349 | "tool_calls": [{"id": id, "type": "function", "function": {"name": name, "arguments": arguments}}], |
| 350 | }), |
| 351 | None => json!({"role": "assistant", "content": "Fixture turn complete."}), |
| 352 | }; |
| 353 | let finish = if message.get("tool_calls").is_some() { |
| 354 | "tool_calls" |
| 355 | } else { |
| 356 | "stop" |
| 357 | }; |
| 358 | return write_json( |
| 359 | &mut stream, |
| 360 | "200 OK", |
| 361 | &json!({ |
| 362 | "id": "fixture", |
| 363 | "object": "chat.completion", |
| 364 | "model": MODEL, |
| 365 | "choices": [{"index": 0, "message": message, "finish_reason": finish}], |
| 366 | "usage": {"prompt_tokens": 20, "completion_tokens": 40, "total_tokens": 60}, |
| 367 | }), |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | stream.write_all( |
| 372 | b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-cache\r\nconnection: close\r\n\r\n", |
| 373 | )?; |
| 374 | stream.flush()?; |
| 375 | let finish = if let Some((id, name, arguments)) = tool_call { |
| 376 | send_sse_chunk( |
| 377 | &mut stream, |
| 378 | &json!({ |
| 379 | "id": "fixture", |
| 380 | "object": "chat.completion.chunk", |
| 381 | "model": MODEL, |
| 382 | "choices": [{ |
| 383 | "index": 0, |
| 384 | "delta": { |
| 385 | "tool_calls": [{ |
| 386 | "index": 0, |
| 387 | "id": id, |
| 388 | "type": "function", |
| 389 | "function": {"name": name, "arguments": arguments}, |
| 390 | }] |
| 391 | }, |
| 392 | "finish_reason": null, |
| 393 | }] |
| 394 | }), |
| 395 | )?; |
| 396 | "tool_calls" |
| 397 | } else { |
| 398 | send_sse_chunk( |
| 399 | &mut stream, |
| 400 | &json!({ |
| 401 | "id": "fixture", |
| 402 | "object": "chat.completion.chunk", |
| 403 | "model": MODEL, |
| 404 | "choices": [{ |
| 405 | "index": 0, |
| 406 | "delta": {"content": "Fixture turn complete."}, |
| 407 | "finish_reason": null, |
| 408 | }] |
| 409 | }), |
| 410 | )?; |
| 411 | "stop" |
| 412 | }; |
| 413 | send_sse_chunk( |
| 414 | &mut stream, |
| 415 | &json!({ |
| 416 | "id": "fixture", |
| 417 | "object": "chat.completion.chunk", |
| 418 | "model": MODEL, |
| 419 | "choices": [{"index": 0, "delta": {}, "finish_reason": finish}], |
| 420 | "usage": {"prompt_tokens": 20, "completion_tokens": 40, "total_tokens": 60}, |
| 421 | }), |
| 422 | )?; |
| 423 | stream.write_all(b"data: [DONE]\n\n")?; |
| 424 | stream.flush() |
| 425 | } |
| 426 | |
| 427 | fn send_sse_chunk(stream: &mut TcpStream, chunk: &Value) -> std::io::Result<()> { |
| 428 | stream.write_all(format!("data: {chunk}\n\n").as_bytes())?; |
| 429 | stream.flush() |
| 430 | } |
| 431 | |
| 432 | fn write_json(stream: &mut TcpStream, status: &str, body: &Value) -> std::io::Result<()> { |
| 433 | let body = body.to_string(); |
| 434 | stream.write_all( |
| 435 | format!( |
| 436 | "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", |
| 437 | body.len() |
| 438 | ) |
| 439 | .as_bytes(), |
| 440 | )?; |
| 441 | stream.flush() |
| 442 | } |
| 443 | |
| 444 | fn read_outbox(path: &Path) -> Vec<Value> { |
| 445 | let Ok(raw) = std::fs::read_to_string(path) else { |
| 446 | return Vec::new(); |
| 447 | }; |
| 448 | raw.lines() |
| 449 | .filter(|line| !line.trim().is_empty()) |
| 450 | .map(|line| serde_json::from_str::<Value>(line).expect("valid outbox JSON line")) |
| 451 | .collect() |
| 452 | } |
| 453 | |
| 454 | fn wait_for_turn_ends(tui: &mut Harness, outbox: &Path, count: usize, timeout: Duration) { |
| 455 | tui.wait_for( |
| 456 | |frame| { |
| 457 | assert!( |
| 458 | !frame.contains("Turn dispatch timed out"), |
| 459 | "turn timed out: {}", |
| 460 | frame.text() |
| 461 | ); |
| 462 | read_outbox(outbox) |
| 463 | .iter() |
| 464 | .filter(|event| event["event"] == "turn_end") |
| 465 | .count() |
| 466 | >= count |
| 467 | }, |
| 468 | timeout, |
| 469 | ) |
| 470 | .unwrap_or_else(|error| { |
| 471 | panic!( |
| 472 | "TUI did not finish turn {count}: {error}\n{}", |
| 473 | tui.diagnostics() |
| 474 | ) |
| 475 | }); |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn tui_auto_review_end_to_end_person_messages_block_and_retry() { |
| 480 | let wait = ci_scaled(Duration::from_secs(30)); |
| 481 | let workspace = make_sealed_workspace().expect("sealed workspace"); |
| 482 | let provider = MockProvider::start(); |
| 483 | let outbox = workspace.home().join("turn-receipts.jsonl"); |
| 484 | std::fs::write(workspace.home().join(".codewhale/.onboarded"), "").expect("onboarded"); |
| 485 | std::fs::write( |
| 486 | workspace.home().join(".codewhale/settings.toml"), |
| 487 | "permission_posture = \"auto_review\"\n", |
| 488 | ) |
| 489 | .expect("settings"); |
| 490 | let config = format!( |
| 491 | r#"provider = "fixture" |
| 492 | default_text_model = "{MODEL}" |
| 493 | prompt_suggestion = false |
| 494 | allow_shell = true |
| 495 | telemetry = false |
| 496 | |
| 497 | [providers.fixture] |
| 498 | kind = "openai-compatible" |
| 499 | base_url = {base_url} |
| 500 | api_key = "synthetic-auto-review-key" |
| 501 | model = "{MODEL}" |
| 502 | |
| 503 | [auto_review] |
| 504 | review_all_shell = true |
| 505 | |
| 506 | [retry] |
| 507 | enabled = false |
| 508 | |
| 509 | [notifications] |
| 510 | method = "off" |
| 511 | completion_sound = "off" |
| 512 | |
| 513 | [lifecycle_outbox] |
| 514 | path = {outbox} |
| 515 | "#, |
| 516 | base_url = json!(provider.base_url()), |
| 517 | outbox = json!(outbox), |
| 518 | ); |
| 519 | std::fs::write(workspace.home().join(".codewhale/config.toml"), config).expect("config"); |
| 520 | workspace.trust_workspace().expect("trust workspace"); |
| 521 | |
| 522 | let mut tui = Harness::builder(crate::binary::codewhale()) |
| 523 | .cwd(workspace.workspace()) |
| 524 | .clear_env() |
| 525 | .seal_home(workspace.home()) |
| 526 | .env( |
| 527 | "PATH", |
| 528 | std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin:/usr/sbin:/sbin".to_string()), |
| 529 | ) |
| 530 | .env("CODEWHALE_DISABLE_MODELS_DEV_FETCH", "1") |
| 531 | .env("CODEWHALE_NO_UPDATE_CHECK", "1") |
| 532 | .env("CODEWHALE_DISABLE_LOCAL_OLLAMA_PROBE", "1") |
| 533 | .env("NO_ANIMATIONS", "1") |
| 534 | .env("NO_PROXY", "*,127.0.0.1") |
| 535 | .args([ |
| 536 | "--workspace", |
| 537 | workspace.workspace().to_str().expect("workspace UTF-8"), |
| 538 | "--no-project-config", |
| 539 | "--skip-onboarding", |
| 540 | "--fresh", |
| 541 | "--permission-mode", |
| 542 | "auto-review", |
| 543 | ]) |
| 544 | .size(40, 120) |
| 545 | .spawn() |
| 546 | .expect("spawn TUI"); |
| 547 | |
| 548 | tui.wait_for_text("Describe a task", wait) |
| 549 | .expect("ready composer"); |
| 550 | |
| 551 | let safe_path = workspace.workspace().join("safe-canary.txt"); |
| 552 | let danger_path = workspace.workspace().join("danger-canary.txt"); |
| 553 | let retried_path = workspace.workspace().join("retried-canary.txt"); |
| 554 | |
| 555 | tui.type_line(SAFE_PROMPT).expect("send safe prompt"); |
| 556 | wait_for_turn_ends(&mut tui, &outbox, 1, wait); |
| 557 | assert!(safe_path.is_file(), "requested safe command must execute"); |
| 558 | assert_eq!(std::fs::read_to_string(&safe_path).unwrap(), "safe"); |
| 559 | |
| 560 | tui.type_line(DANGER_PROMPT).expect("send danger prompt"); |
| 561 | wait_for_turn_ends(&mut tui, &outbox, 2, wait); |
| 562 | assert!( |
| 563 | !danger_path.exists(), |
| 564 | "dangerous unrequested command must stay blocked" |
| 565 | ); |
| 566 | |
| 567 | tui.type_line(RETRY_PROMPT) |
| 568 | .expect("send retry-target prompt"); |
| 569 | wait_for_turn_ends(&mut tui, &outbox, 3, wait); |
| 570 | assert!( |
| 571 | !retried_path.exists(), |
| 572 | "held command must not run before approval" |
| 573 | ); |
| 574 | tui.wait_for( |
| 575 | |frame| { |
| 576 | frame |
| 577 | .text() |
| 578 | .split_whitespace() |
| 579 | .collect::<Vec<_>>() |
| 580 | .join(" ") |
| 581 | .contains("/permissions blocked approve") |
| 582 | }, |
| 583 | wait, |
| 584 | ) |
| 585 | .expect("retry hint rendered in TUI"); |
| 586 | |
| 587 | tui.type_line("/permissions blocked approve") |
| 588 | .expect("approve the latest one-time retry"); |
| 589 | tui.wait_for( |
| 590 | |frame| { |
| 591 | frame |
| 592 | .text() |
| 593 | .split_whitespace() |
| 594 | .collect::<Vec<_>>() |
| 595 | .join(" ") |
| 596 | .contains("Approved one retry of") |
| 597 | }, |
| 598 | wait, |
| 599 | ) |
| 600 | .expect("TUI status confirms one-time retry approval"); |
| 601 | |
| 602 | tui.type_line(FOLLOWUP_PROMPT) |
| 603 | .expect("send follow-up retry turn"); |
| 604 | wait_for_turn_ends(&mut tui, &outbox, 4, wait); |
| 605 | assert!( |
| 606 | retried_path.is_file(), |
| 607 | "approved retry command must execute" |
| 608 | ); |
| 609 | assert_eq!(std::fs::read_to_string(&retried_path).unwrap(), "retried"); |
| 610 | |
| 611 | let records = provider.records(); |
| 612 | let safe_rec = records |
| 613 | .iter() |
| 614 | .find(|r| r.proposed.contains("safe-canary.txt")) |
| 615 | .expect("guardian saw safe command"); |
| 616 | assert_eq!(safe_rec.decision, "allow", "{safe_rec:?}"); |
| 617 | assert!( |
| 618 | safe_rec |
| 619 | .person_messages |
| 620 | .iter() |
| 621 | .any(|m| m.contains("safe-canary.txt")), |
| 622 | "guardian must see person message for safe command: {safe_rec:?}" |
| 623 | ); |
| 624 | |
| 625 | let danger_rec = records |
| 626 | .iter() |
| 627 | .find(|r| r.proposed.contains("danger-canary.txt")) |
| 628 | .expect("guardian saw dangerous command"); |
| 629 | assert_eq!(danger_rec.decision, "deny", "{danger_rec:?}"); |
| 630 | assert!( |
| 631 | danger_rec |
| 632 | .person_messages |
| 633 | .iter() |
| 634 | .any(|m| m.contains(DANGER_PROMPT)), |
| 635 | "guardian must see person message on dangerous command: {danger_rec:?}" |
| 636 | ); |
| 637 | |
| 638 | let retry_records: Vec<&GuardianRecord> = records |
| 639 | .iter() |
| 640 | .filter(|r| r.proposed.contains("retried-canary.txt")) |
| 641 | .collect(); |
| 642 | assert_eq!(retry_records.len(), 2, "{retry_records:#?}"); |
| 643 | assert_eq!(retry_records[0].decision, "deny"); |
| 644 | assert!(!retry_records[0].person_approved_retry); |
| 645 | assert_eq!(retry_records[1].decision, "allow"); |
| 646 | assert!(retry_records[1].person_approved_retry); |
| 647 | |
| 648 | println!( |
| 649 | "AUTO_REVIEW_ACCEPTANCE_RECEIPT: safe={:?} danger={:?} held={:?} retried={:?}", |
| 650 | safe_rec.reason, danger_rec.reason, retry_records[0].reason, retry_records[1].reason |
| 651 | ); |
| 652 | |
| 653 | tui.shutdown(); |
| 654 | } |
| 655 |