| 1 | //! Model-backed Auto-Review guardian tier (v0.9.8). |
| 2 | //! |
| 3 | //! The deterministic policy engine (see [`crate::core::authority::auto_review`]) decides |
| 4 | //! first: configured block rules and the built-in safety floor are hard |
| 5 | //! blocks that never reach a model. Only deterministic *fallback holds* — the |
| 6 | //! `AskUser` outcomes Auto posture would otherwise turn into bare permission |
| 7 | //! denials — escalate to a one-shot reviewer request. A denial returns the |
| 8 | //! rule and rationale while inviting another route or person approval, |
| 9 | //! and any reviewer failure (timeout, transport error, unparseable answer) |
| 10 | //! is a denial — fail closed. The reviewer is deliberately stateless: each |
| 11 | //! proposed call stands on its own deterministic context. |
| 12 | |
| 13 | use std::time::Duration; |
| 14 | |
| 15 | use crate::core::authority::auto_review::{ |
| 16 | AutoReviewAction, DEFAULT_GUARDIAN_POLICY, MAX_REVIEW_CONTEXT_BYTES, ReviewerRiskLevel, |
| 17 | ReviewerVerdict, SUBAGENT_RETURN_GUARDIAN_POLICY, parse_reviewer_verdict, |
| 18 | }; |
| 19 | use crate::core::model_client::ModelClient; |
| 20 | use crate::tools::spec::ToolError; |
| 21 | use codewhale_models::Role; |
| 22 | use codewhale_models::{ |
| 23 | ContentBlock, Message, MessageRequest, MessageResponse, SystemPrompt, Usage, |
| 24 | is_incomplete_stop_reason, |
| 25 | }; |
| 26 | use tokio_util::sync::CancellationToken; |
| 27 | |
| 28 | /// One-shot reviewer deadline. Slow reviewers are denials, surfaced |
| 29 | /// separately from explicit denials (a timeout proves nothing about safety). |
| 30 | const REVIEWER_TIMEOUT: Duration = Duration::from_secs(90); |
| 31 | const REVIEWER_MAX_OUTPUT_TOKENS: u32 = 4096; |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum ReviewerFailureKind { |
| 35 | Transport, |
| 36 | Unparseable, |
| 37 | Incomplete, |
| 38 | OverBudget, |
| 39 | } |
| 40 | |
| 41 | impl ReviewerFailureKind { |
| 42 | pub fn as_str(self) -> &'static str { |
| 43 | match self { |
| 44 | Self::Transport => "transport", |
| 45 | Self::Unparseable => "unparseable", |
| 46 | Self::Incomplete => "incomplete", |
| 47 | Self::OverBudget => "over_budget", |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | pub fn label(self) -> &'static str { |
| 52 | match self { |
| 53 | Self::Transport => "transport error", |
| 54 | Self::Unparseable => "unparseable answer", |
| 55 | Self::Incomplete => "incomplete answer", |
| 56 | Self::OverBudget => "review context over budget", |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 62 | pub enum ReviewerOutcome { |
| 63 | Allow { |
| 64 | risk: ReviewerRiskLevel, |
| 65 | reason: String, |
| 66 | }, |
| 67 | Deny { |
| 68 | risk: ReviewerRiskLevel, |
| 69 | reason: String, |
| 70 | }, |
| 71 | TimedOut { |
| 72 | reason: String, |
| 73 | }, |
| 74 | Failed { |
| 75 | kind: ReviewerFailureKind, |
| 76 | reason: String, |
| 77 | }, |
| 78 | Cancelled, |
| 79 | } |
| 80 | |
| 81 | impl ReviewerOutcome { |
| 82 | pub fn audit_decision(&self) -> &'static str { |
| 83 | match self { |
| 84 | Self::Allow { .. } => "allow", |
| 85 | Self::Deny { .. } => "deny", |
| 86 | Self::TimedOut { .. } => "timed_out", |
| 87 | Self::Failed { .. } => "failed", |
| 88 | Self::Cancelled => "cancelled", |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | pub fn audit_risk(&self) -> Option<&'static str> { |
| 93 | match self { |
| 94 | Self::Allow { risk, .. } | Self::Deny { risk, .. } => Some(risk.as_str()), |
| 95 | Self::TimedOut { .. } | Self::Failed { .. } | Self::Cancelled => None, |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | pub fn failure_reason(&self) -> Option<&str> { |
| 100 | match self { |
| 101 | Self::TimedOut { reason } | Self::Failed { reason, .. } => Some(reason), |
| 102 | Self::Allow { .. } | Self::Deny { .. } | Self::Cancelled => None, |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | pub fn failure_prompt_kind(&self) -> Option<&'static str> { |
| 107 | match self { |
| 108 | Self::TimedOut { .. } => Some("timed out"), |
| 109 | Self::Failed { kind, .. } => Some(kind.label()), |
| 110 | Self::Allow { .. } | Self::Deny { .. } | Self::Cancelled => None, |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | pub fn into_tool_result(self, tool_name: &str) -> Result<String, ToolError> { |
| 115 | self.into_tool_result_with_rule(tool_name, None) |
| 116 | } |
| 117 | |
| 118 | pub fn into_tool_result_with_rule( |
| 119 | self, |
| 120 | _tool_name: &str, |
| 121 | rule: Option<&str>, |
| 122 | ) -> Result<String, ToolError> { |
| 123 | match self { |
| 124 | Self::Allow { reason, .. } => Ok(reason), |
| 125 | Self::Deny { reason, .. } => Err(ToolError::permission_denied( |
| 126 | crate::core::authority::auto_review::format_auto_review_block_message( |
| 127 | &reason, |
| 128 | rule.or(Some("guardian")), |
| 129 | ), |
| 130 | )), |
| 131 | Self::TimedOut { reason } => Err(ToolError::permission_denied(format!( |
| 132 | "Auto-Review could not complete (timed out: {reason}), so the call was denied (fail closed). This is a review failure, not a determination that the action is unsafe. Do not bypass the approval check; retry once, resolve the error, or ask the user." |
| 133 | ))), |
| 134 | Self::Failed { kind, reason } => Err(ToolError::permission_denied(format!( |
| 135 | "Auto-Review could not complete (failed: {}: {reason}), so the call was denied (fail closed). This is a review failure, not a determination that the action is unsafe. Do not bypass the approval check; retry once, resolve the error, or ask the user.", |
| 136 | kind.as_str() |
| 137 | ))), |
| 138 | Self::Cancelled => Err(ToolError::cancelled( |
| 139 | "Auto-Review guardian request cancelled", |
| 140 | )), |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 146 | pub struct ReviewerResult { |
| 147 | pub outcome: ReviewerOutcome, |
| 148 | pub usage: Option<Usage>, |
| 149 | pub reviewer_model: String, |
| 150 | pub attempts: u8, |
| 151 | } |
| 152 | |
| 153 | impl ReviewerResult { |
| 154 | fn finish( |
| 155 | outcome: ReviewerOutcome, |
| 156 | usage: Option<Usage>, |
| 157 | reviewer_model: String, |
| 158 | attempts: u8, |
| 159 | ) -> Self { |
| 160 | Self { |
| 161 | outcome, |
| 162 | usage, |
| 163 | reviewer_model, |
| 164 | attempts, |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | fn timed_out( |
| 169 | reason: impl Into<String>, |
| 170 | usage: Option<Usage>, |
| 171 | reviewer_model: String, |
| 172 | attempts: u8, |
| 173 | ) -> Self { |
| 174 | Self::finish( |
| 175 | ReviewerOutcome::TimedOut { |
| 176 | reason: reason.into(), |
| 177 | }, |
| 178 | usage, |
| 179 | reviewer_model, |
| 180 | attempts, |
| 181 | ) |
| 182 | } |
| 183 | |
| 184 | fn failed( |
| 185 | kind: ReviewerFailureKind, |
| 186 | reason: impl Into<String>, |
| 187 | usage: Option<Usage>, |
| 188 | reviewer_model: String, |
| 189 | attempts: u8, |
| 190 | ) -> Self { |
| 191 | Self::finish( |
| 192 | ReviewerOutcome::Failed { |
| 193 | kind, |
| 194 | reason: reason.into(), |
| 195 | }, |
| 196 | usage, |
| 197 | reviewer_model, |
| 198 | attempts, |
| 199 | ) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | pub fn resolve_reviewer_model(configured: Option<&str>, client: &dyn ModelClient) -> String { |
| 204 | if let Some(explicit) = configured.map(str::trim).filter(|s| !s.is_empty()) { |
| 205 | return explicit.to_string(); |
| 206 | } |
| 207 | let provider = client |
| 208 | .provider_name() |
| 209 | .trim() |
| 210 | .to_ascii_lowercase() |
| 211 | .replace('_', "-"); |
| 212 | let candidates: &[&str] = match provider.as_str() { |
| 213 | "anthropic" => &["claude-sonnet-5-5", "claude-sonnet-4-6"], |
| 214 | "openai" => &["gpt-5.6", "gpt-5.5"], |
| 215 | "openai-codex" => &["gpt-6.1-sol", "gpt-5.3-codex", "gpt-5.6"], |
| 216 | "deepseek" | "deepseek-anthropic" => &["deepseek-v4-pro"], |
| 217 | "google" => &["gemini-3.1-pro-preview", "gemini-4-argon"], |
| 218 | "openrouter" => &["deepseek/deepseek-v4-pro"], |
| 219 | "xai" => &["grok-4.7"], |
| 220 | "zai" => &["GLM-5.3"], |
| 221 | "moonshot" => &["kimi-k3.1-pro"], |
| 222 | "minimax" | "minimax-anthropic" => &["MiniMax-M3"], |
| 223 | _ => &[], |
| 224 | }; |
| 225 | for &candidate in candidates { |
| 226 | if client.supports_catalog_reviewer_model(candidate) { |
| 227 | return candidate.to_string(); |
| 228 | } |
| 229 | } |
| 230 | client.model().to_string() |
| 231 | } |
| 232 | |
| 233 | pub async fn consult_reviewer( |
| 234 | client: &dyn ModelClient, |
| 235 | context_text: &str, |
| 236 | cancel_token: &CancellationToken, |
| 237 | ) -> ReviewerResult { |
| 238 | consult_reviewer_with_model_and_retry(client, None, context_text, cancel_token, false).await |
| 239 | } |
| 240 | |
| 241 | pub async fn consult_reviewer_with_model( |
| 242 | client: &dyn ModelClient, |
| 243 | configured_model: Option<&str>, |
| 244 | context_text: &str, |
| 245 | cancel_token: &CancellationToken, |
| 246 | ) -> ReviewerResult { |
| 247 | consult_reviewer_with_model_and_retry( |
| 248 | client, |
| 249 | configured_model, |
| 250 | context_text, |
| 251 | cancel_token, |
| 252 | false, |
| 253 | ) |
| 254 | .await |
| 255 | } |
| 256 | |
| 257 | pub async fn consult_reviewer_with_retry_approval( |
| 258 | client: &dyn ModelClient, |
| 259 | context_text: &str, |
| 260 | cancel_token: &CancellationToken, |
| 261 | person_approved_retry: bool, |
| 262 | ) -> ReviewerResult { |
| 263 | consult_reviewer_with_model_and_retry( |
| 264 | client, |
| 265 | None, |
| 266 | context_text, |
| 267 | cancel_token, |
| 268 | person_approved_retry, |
| 269 | ) |
| 270 | .await |
| 271 | } |
| 272 | |
| 273 | pub async fn consult_subagent_return_reviewer( |
| 274 | client: &dyn ModelClient, |
| 275 | configured_model: Option<&str>, |
| 276 | context_text: &str, |
| 277 | cancel_token: &CancellationToken, |
| 278 | ) -> ReviewerResult { |
| 279 | consult_reviewer_inner( |
| 280 | client, |
| 281 | configured_model, |
| 282 | SUBAGENT_RETURN_GUARDIAN_POLICY, |
| 283 | context_text, |
| 284 | cancel_token, |
| 285 | false, |
| 286 | ) |
| 287 | .await |
| 288 | } |
| 289 | |
| 290 | pub async fn consult_reviewer_with_model_and_retry( |
| 291 | client: &dyn ModelClient, |
| 292 | configured_model: Option<&str>, |
| 293 | context_text: &str, |
| 294 | cancel_token: &CancellationToken, |
| 295 | person_approved_retry: bool, |
| 296 | ) -> ReviewerResult { |
| 297 | consult_reviewer_inner( |
| 298 | client, |
| 299 | configured_model, |
| 300 | DEFAULT_GUARDIAN_POLICY, |
| 301 | context_text, |
| 302 | cancel_token, |
| 303 | person_approved_retry, |
| 304 | ) |
| 305 | .await |
| 306 | } |
| 307 | |
| 308 | async fn consult_reviewer_inner( |
| 309 | client: &dyn ModelClient, |
| 310 | configured_model: Option<&str>, |
| 311 | system_policy: &str, |
| 312 | context_text: &str, |
| 313 | cancel_token: &CancellationToken, |
| 314 | person_approved_retry: bool, |
| 315 | ) -> ReviewerResult { |
| 316 | consult_reviewer_inner_with_timeout( |
| 317 | client, |
| 318 | configured_model, |
| 319 | system_policy, |
| 320 | context_text, |
| 321 | cancel_token, |
| 322 | person_approved_retry, |
| 323 | REVIEWER_TIMEOUT, |
| 324 | ) |
| 325 | .await |
| 326 | } |
| 327 | |
| 328 | async fn consult_reviewer_inner_with_timeout( |
| 329 | client: &dyn ModelClient, |
| 330 | configured_model: Option<&str>, |
| 331 | system_policy: &str, |
| 332 | context_text: &str, |
| 333 | cancel_token: &CancellationToken, |
| 334 | person_approved_retry: bool, |
| 335 | total_timeout: Duration, |
| 336 | ) -> ReviewerResult { |
| 337 | let model = resolve_reviewer_model(configured_model, client); |
| 338 | if context_text.len() > MAX_REVIEW_CONTEXT_BYTES { |
| 339 | return ReviewerResult::failed( |
| 340 | ReviewerFailureKind::OverBudget, |
| 341 | "the exact review context exceeded the guardian limit", |
| 342 | None, |
| 343 | model, |
| 344 | 0, |
| 345 | ); |
| 346 | } |
| 347 | let deepseek = client.provider_name() == codewhale_config::ProviderKind::Deepseek.as_str(); |
| 348 | let reasoning_effort = deepseek.then(|| "low".to_string()); |
| 349 | let temperature = reasoning_effort.is_none().then_some(0.0); |
| 350 | let request = MessageRequest { |
| 351 | model: model.clone(), |
| 352 | messages: vec![Message { |
| 353 | role: Role::User, |
| 354 | content: vec![ContentBlock::Text { |
| 355 | text: context_text.to_string(), |
| 356 | cache_control: None, |
| 357 | }], |
| 358 | }], |
| 359 | max_tokens: REVIEWER_MAX_OUTPUT_TOKENS, |
| 360 | system: Some(SystemPrompt::Text(system_policy.to_string())), |
| 361 | tools: None, |
| 362 | tool_choice: None, |
| 363 | metadata: None, |
| 364 | thinking: None, |
| 365 | reasoning_effort, |
| 366 | stream: Some(false), |
| 367 | temperature, |
| 368 | top_p: None, |
| 369 | safety_check: None, |
| 370 | title: None, |
| 371 | }; |
| 372 | if cancel_token.is_cancelled() { |
| 373 | return ReviewerResult::finish(ReviewerOutcome::Cancelled, None, model, 0); |
| 374 | } |
| 375 | let deadline = tokio::time::Instant::now() + total_timeout; |
| 376 | let per_attempt_timeout = total_timeout / 2; |
| 377 | let mut attempts: u8 = 0; |
| 378 | loop { |
| 379 | attempts = attempts.saturating_add(1); |
| 380 | let now = tokio::time::Instant::now(); |
| 381 | if now >= deadline { |
| 382 | return ReviewerResult::timed_out("the reviewer timed out", None, model, attempts); |
| 383 | } |
| 384 | let attempt_deadline = if attempts == 1 { |
| 385 | (now + per_attempt_timeout).min(deadline) |
| 386 | } else { |
| 387 | deadline |
| 388 | }; |
| 389 | let response = tokio::select! { |
| 390 | biased; |
| 391 | _ = cancel_token.cancelled() => { |
| 392 | return ReviewerResult::finish(ReviewerOutcome::Cancelled, None, model, attempts); |
| 393 | } |
| 394 | response = tokio::time::timeout_at(attempt_deadline, client.create_message_uncached(request.clone())) => response, |
| 395 | }; |
| 396 | match response { |
| 397 | Err(_) => { |
| 398 | if attempts < 2 |
| 399 | && tokio::time::Instant::now() < deadline |
| 400 | && !cancel_token.is_cancelled() |
| 401 | { |
| 402 | continue; |
| 403 | } |
| 404 | return ReviewerResult::timed_out("the reviewer timed out", None, model, attempts); |
| 405 | } |
| 406 | Ok(Err(_)) => { |
| 407 | if attempts < 2 |
| 408 | && tokio::time::Instant::now() < deadline |
| 409 | && !cancel_token.is_cancelled() |
| 410 | { |
| 411 | continue; |
| 412 | } |
| 413 | return ReviewerResult::failed( |
| 414 | ReviewerFailureKind::Transport, |
| 415 | "the reviewer request failed", |
| 416 | None, |
| 417 | model, |
| 418 | attempts, |
| 419 | ); |
| 420 | } |
| 421 | Ok(Ok(response)) => { |
| 422 | let outcome = verdict_from_response(&response, person_approved_retry); |
| 423 | return ReviewerResult::finish(outcome, Some(response.usage), model, attempts); |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | fn verdict_from_response( |
| 430 | response: &MessageResponse, |
| 431 | person_approved_retry: bool, |
| 432 | ) -> ReviewerOutcome { |
| 433 | if is_incomplete_stop_reason(response.stop_reason.as_deref()) { |
| 434 | return ReviewerOutcome::Failed { |
| 435 | kind: ReviewerFailureKind::Incomplete, |
| 436 | reason: "the reviewer answer was incomplete".to_string(), |
| 437 | }; |
| 438 | } |
| 439 | let text: String = response |
| 440 | .content |
| 441 | .iter() |
| 442 | .filter_map(|block| match block { |
| 443 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 444 | _ => None, |
| 445 | }) |
| 446 | .collect::<Vec<_>>() |
| 447 | .join("\n"); |
| 448 | match parse_reviewer_verdict(&text) { |
| 449 | Some(ReviewerVerdict { |
| 450 | action: AutoReviewAction::Allow, |
| 451 | risk, |
| 452 | reason, |
| 453 | }) if risk.may_auto_run() || person_approved_retry => { |
| 454 | ReviewerOutcome::Allow { risk, reason } |
| 455 | } |
| 456 | Some(ReviewerVerdict { |
| 457 | action: AutoReviewAction::Allow, |
| 458 | risk, |
| 459 | .. |
| 460 | }) => ReviewerOutcome::Deny { |
| 461 | risk, |
| 462 | reason: format!( |
| 463 | "the reviewer classified the call as {} risk, which Auto-Review cannot run automatically", |
| 464 | risk.as_str() |
| 465 | ), |
| 466 | }, |
| 467 | Some(ReviewerVerdict { |
| 468 | action: AutoReviewAction::Block, |
| 469 | risk, |
| 470 | reason, |
| 471 | }) => ReviewerOutcome::Deny { risk, reason }, |
| 472 | Some(_) | None => ReviewerOutcome::Failed { |
| 473 | kind: ReviewerFailureKind::Unparseable, |
| 474 | reason: format!("the reviewer answer was unparseable ({} chars)", text.len()), |
| 475 | }, |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | #[cfg(test)] |
| 480 | mod tests { |
| 481 | use super::*; |
| 482 | use crate::llm_client::mock::MockLlmClient; |
| 483 | |
| 484 | fn response(text: &str, usage: Usage) -> MessageResponse { |
| 485 | MessageResponse { |
| 486 | tool_projection_warning: None, |
| 487 | id: "review".to_string(), |
| 488 | r#type: "message".to_string(), |
| 489 | role: "assistant".to_string(), |
| 490 | content: vec![ContentBlock::Text { |
| 491 | text: text.to_string(), |
| 492 | cache_control: None, |
| 493 | }], |
| 494 | model: "mock-model".to_string(), |
| 495 | stop_reason: Some("end_turn".to_string()), |
| 496 | stop_sequence: None, |
| 497 | container: None, |
| 498 | usage, |
| 499 | title: None, |
| 500 | stop_details: None, |
| 501 | refusal: None, |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | #[tokio::test] |
| 506 | async fn guardian_rechecks_identical_calls_instead_of_reusing_a_cached_allow() { |
| 507 | use wiremock::matchers::method; |
| 508 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 509 | |
| 510 | let server = MockServer::start().await; |
| 511 | let client = crate::client::CodewhaleClient::new( |
| 512 | &<codewhale_runtime::config::Config as Default>::default().with_legacy_root( |
| 513 | Some("test-guardian-cache-key".to_string()), |
| 514 | Some(server.uri()), |
| 515 | ), |
| 516 | ) |
| 517 | .unwrap(); |
| 518 | for (decision, risk) in [("allow", "low"), ("deny", "high")] { |
| 519 | server.reset().await; |
| 520 | let verdict = serde_json::json!({ |
| 521 | "decision": decision, |
| 522 | "risk_level": risk, |
| 523 | "reason": "current authorization evidence", |
| 524 | }); |
| 525 | Mock::given(method("POST")) |
| 526 | .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ |
| 527 | "id": "guardian-fresh", |
| 528 | "object": "chat.completion", |
| 529 | "model": "deepseek-v4-pro", |
| 530 | "choices": [{"index": 0, "message": { |
| 531 | "role": "assistant", "content": verdict.to_string(), |
| 532 | }, "finish_reason": "stop"}], |
| 533 | "usage": {"prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12}, |
| 534 | }))) |
| 535 | .mount(&server) |
| 536 | .await; |
| 537 | let result = consult_reviewer( |
| 538 | &client, |
| 539 | "the same proposed call under current policy", |
| 540 | &CancellationToken::new(), |
| 541 | ) |
| 542 | .await; |
| 543 | assert_eq!(result.outcome.audit_decision(), decision); |
| 544 | assert_eq!(result.usage.unwrap().output_tokens, 3); |
| 545 | assert_eq!(server.received_requests().await.unwrap().len(), 1); |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | #[tokio::test] |
| 550 | async fn reviewer_records_usage_and_keeps_context_untrusted() { |
| 551 | let usage = Usage { |
| 552 | input_tokens: 17, |
| 553 | output_tokens: 9, |
| 554 | ..Usage::default() |
| 555 | }; |
| 556 | let mock = MockLlmClient::new(Vec::new()); |
| 557 | mock.push_message_response(response( |
| 558 | r#"{"risk_level":"low","decision":"allow","reason":"bounded and authorized"}"#, |
| 559 | usage.clone(), |
| 560 | )); |
| 561 | |
| 562 | let result = consult_reviewer( |
| 563 | &mock, |
| 564 | r#"{"proposed_tool_call":{"tool":"exec_shell"}}"#, |
| 565 | &CancellationToken::new(), |
| 566 | ) |
| 567 | .await; |
| 568 | |
| 569 | assert_eq!( |
| 570 | result.outcome, |
| 571 | ReviewerOutcome::Allow { |
| 572 | risk: ReviewerRiskLevel::Low, |
| 573 | reason: "bounded and authorized".to_string() |
| 574 | } |
| 575 | ); |
| 576 | assert_eq!(result.usage, Some(usage)); |
| 577 | let request = mock.last_request().expect("reviewer request"); |
| 578 | assert_eq!(request.tools, None, "guardian requests never expose tools"); |
| 579 | let SystemPrompt::Text(system) = request.system.expect("guardian policy") else { |
| 580 | panic!("guardian system prompt must be text"); |
| 581 | }; |
| 582 | assert!(system.contains("Judge the proposed call against")); |
| 583 | assert!(system.contains("Never invent facts")); |
| 584 | assert!(!system.contains("Never infer user intent")); |
| 585 | } |
| 586 | |
| 587 | #[tokio::test] |
| 588 | async fn reviewer_distinguishes_denial_malformed_and_incomplete_answers() { |
| 589 | let deny = MockLlmClient::new(Vec::new()); |
| 590 | deny.push_message_response(response( |
| 591 | r#"{"risk_level":"high","decision":"deny","reason":"destination is not authorized"}"#, |
| 592 | Usage::default(), |
| 593 | )); |
| 594 | assert_eq!( |
| 595 | consult_reviewer(&deny, "context", &CancellationToken::new()) |
| 596 | .await |
| 597 | .outcome, |
| 598 | ReviewerOutcome::Deny { |
| 599 | risk: ReviewerRiskLevel::High, |
| 600 | reason: "destination is not authorized".to_string() |
| 601 | } |
| 602 | ); |
| 603 | assert!(matches!( |
| 604 | verdict_from_response( |
| 605 | &response( |
| 606 | r#"{"risk_level":"high","decision":"allow","reason":"the request mentions it"}"#, |
| 607 | Usage::default(), |
| 608 | ), |
| 609 | false, |
| 610 | ), |
| 611 | ReviewerOutcome::Deny { |
| 612 | risk: ReviewerRiskLevel::High, |
| 613 | .. |
| 614 | } |
| 615 | )); |
| 616 | assert_eq!( |
| 617 | verdict_from_response( |
| 618 | &response( |
| 619 | r#"{"risk_level":"high","decision":"allow","reason":"person approved retry"}"#, |
| 620 | Usage::default(), |
| 621 | ), |
| 622 | true, |
| 623 | ), |
| 624 | ReviewerOutcome::Allow { |
| 625 | risk: ReviewerRiskLevel::High, |
| 626 | reason: "person approved retry".to_string(), |
| 627 | } |
| 628 | ); |
| 629 | assert!(matches!( |
| 630 | verdict_from_response( |
| 631 | &response( |
| 632 | r#"{"risk_level":"high","decision":"deny","reason":"still dangerous"}"#, |
| 633 | Usage::default(), |
| 634 | ), |
| 635 | true, |
| 636 | ), |
| 637 | ReviewerOutcome::Deny { |
| 638 | risk: ReviewerRiskLevel::High, |
| 639 | .. |
| 640 | } |
| 641 | )); |
| 642 | |
| 643 | let malformed = MockLlmClient::new(Vec::new()); |
| 644 | malformed.push_message_response(response("allow it", Usage::default())); |
| 645 | let malformed_result = |
| 646 | consult_reviewer(&malformed, "context", &CancellationToken::new()).await; |
| 647 | assert!(matches!( |
| 648 | malformed_result.outcome, |
| 649 | ReviewerOutcome::Failed { |
| 650 | kind: ReviewerFailureKind::Unparseable, |
| 651 | .. |
| 652 | } |
| 653 | )); |
| 654 | assert_eq!(malformed_result.attempts, 1); |
| 655 | assert!(malformed_result.usage.is_some()); |
| 656 | |
| 657 | let incomplete = MockLlmClient::new(Vec::new()); |
| 658 | let mut incomplete_response = response( |
| 659 | r#"{"risk_level":"low","decision":"allow","reason":"looks safe"}"#, |
| 660 | Usage::default(), |
| 661 | ); |
| 662 | incomplete_response.stop_reason = Some("max_tokens".to_string()); |
| 663 | incomplete.push_message_response(incomplete_response); |
| 664 | assert_eq!( |
| 665 | consult_reviewer(&incomplete, "context", &CancellationToken::new()) |
| 666 | .await |
| 667 | .outcome, |
| 668 | ReviewerOutcome::Failed { |
| 669 | kind: ReviewerFailureKind::Incomplete, |
| 670 | reason: "the reviewer answer was incomplete".to_string() |
| 671 | } |
| 672 | ); |
| 673 | } |
| 674 | |
| 675 | #[test] |
| 676 | fn block_texts_name_a_way_forward_without_full_access() { |
| 677 | let deny = ReviewerOutcome::Deny { |
| 678 | risk: ReviewerRiskLevel::High, |
| 679 | reason: "writes outside the workspace".to_string(), |
| 680 | } |
| 681 | .into_tool_result("bash") |
| 682 | .unwrap_err() |
| 683 | .to_string(); |
| 684 | assert!(deny.contains("Auto-Review blocked this:"), "{deny}"); |
| 685 | assert!(deny.contains("writes outside the workspace"), "{deny}"); |
| 686 | assert!(deny.contains("[guardian]"), "{deny}"); |
| 687 | assert!( |
| 688 | deny.contains("The person can approve it from the receipt"), |
| 689 | "{deny}" |
| 690 | ); |
| 691 | assert!(!deny.contains("do not work around"), "{deny}"); |
| 692 | assert!(!deny.contains("Full Access"), "{deny}"); |
| 693 | |
| 694 | let timed_out = ReviewerOutcome::TimedOut { |
| 695 | reason: "timeout".to_string(), |
| 696 | } |
| 697 | .into_tool_result("bash") |
| 698 | .unwrap_err() |
| 699 | .to_string(); |
| 700 | assert!( |
| 701 | timed_out.contains( |
| 702 | "This is a review failure, not a determination that the action is unsafe" |
| 703 | ), |
| 704 | "{timed_out}" |
| 705 | ); |
| 706 | assert!(!timed_out.contains("Full Access"), "{timed_out}"); |
| 707 | assert!(!timed_out.contains("do not work around"), "{timed_out}"); |
| 708 | } |
| 709 | |
| 710 | #[tokio::test] |
| 711 | async fn reviewer_cancellation_aborts_without_calling_provider() { |
| 712 | let mock = MockLlmClient::new(Vec::new()); |
| 713 | let cancel = CancellationToken::new(); |
| 714 | cancel.cancel(); |
| 715 | |
| 716 | let result = consult_reviewer(&mock, "context", &cancel).await; |
| 717 | |
| 718 | assert_eq!(result.outcome, ReviewerOutcome::Cancelled); |
| 719 | assert_eq!(result.attempts, 0); |
| 720 | assert!(result.usage.is_none()); |
| 721 | assert_eq!(mock.call_count(), 0); |
| 722 | } |
| 723 | |
| 724 | #[tokio::test] |
| 725 | async fn reviewer_denies_oversized_exact_context_without_calling_provider() { |
| 726 | let mock = MockLlmClient::new(Vec::new()); |
| 727 | let context = "x".repeat(MAX_REVIEW_CONTEXT_BYTES + 1); |
| 728 | |
| 729 | let result = consult_reviewer(&mock, &context, &CancellationToken::new()).await; |
| 730 | |
| 731 | assert_eq!( |
| 732 | result.outcome, |
| 733 | ReviewerOutcome::Failed { |
| 734 | kind: ReviewerFailureKind::OverBudget, |
| 735 | reason: "the exact review context exceeded the guardian limit".to_string() |
| 736 | } |
| 737 | ); |
| 738 | assert_eq!(result.attempts, 0); |
| 739 | assert!(result.usage.is_none()); |
| 740 | assert_eq!(mock.call_count(), 0); |
| 741 | } |
| 742 | |
| 743 | struct StallingReviewerClient { |
| 744 | attempts: std::sync::atomic::AtomicUsize, |
| 745 | } |
| 746 | |
| 747 | #[async_trait::async_trait] |
| 748 | impl ModelClient for StallingReviewerClient { |
| 749 | fn provider_name(&self) -> &str { |
| 750 | "openai" |
| 751 | } |
| 752 | |
| 753 | fn model(&self) -> &str { |
| 754 | "gpt-5.6" |
| 755 | } |
| 756 | |
| 757 | async fn create_message( |
| 758 | &self, |
| 759 | _request: MessageRequest, |
| 760 | ) -> anyhow::Result<MessageResponse> { |
| 761 | self.attempts |
| 762 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 763 | tokio::time::sleep(Duration::from_secs(5)).await; |
| 764 | unreachable!() |
| 765 | } |
| 766 | |
| 767 | async fn create_message_stream( |
| 768 | &self, |
| 769 | _request: MessageRequest, |
| 770 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 771 | unreachable!() |
| 772 | } |
| 773 | |
| 774 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 775 | Ok(true) |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | #[tokio::test] |
| 780 | async fn timeout_retries_once_then_reports_timed_out() { |
| 781 | let client = StallingReviewerClient { |
| 782 | attempts: std::sync::atomic::AtomicUsize::new(0), |
| 783 | }; |
| 784 | let result = consult_reviewer_inner_with_timeout( |
| 785 | &client, |
| 786 | None, |
| 787 | DEFAULT_GUARDIAN_POLICY, |
| 788 | "context", |
| 789 | &CancellationToken::new(), |
| 790 | false, |
| 791 | Duration::from_millis(80), |
| 792 | ) |
| 793 | .await; |
| 794 | assert_eq!(result.attempts, 2); |
| 795 | assert_eq!(client.attempts.load(std::sync::atomic::Ordering::SeqCst), 2); |
| 796 | assert!(matches!(result.outcome, ReviewerOutcome::TimedOut { .. })); |
| 797 | } |
| 798 | |
| 799 | struct RouteStubClient { |
| 800 | provider: &'static str, |
| 801 | session_model: &'static str, |
| 802 | supports_catalog: bool, |
| 803 | seen_models: std::sync::Mutex<Vec<String>>, |
| 804 | } |
| 805 | |
| 806 | impl RouteStubClient { |
| 807 | fn new( |
| 808 | provider: &'static str, |
| 809 | session_model: &'static str, |
| 810 | supports_catalog: bool, |
| 811 | ) -> Self { |
| 812 | Self { |
| 813 | provider, |
| 814 | session_model, |
| 815 | supports_catalog, |
| 816 | seen_models: std::sync::Mutex::new(Vec::new()), |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | #[async_trait::async_trait] |
| 822 | impl ModelClient for RouteStubClient { |
| 823 | fn provider_name(&self) -> &str { |
| 824 | self.provider |
| 825 | } |
| 826 | |
| 827 | fn model(&self) -> &str { |
| 828 | self.session_model |
| 829 | } |
| 830 | |
| 831 | fn supports_catalog_reviewer_model(&self, _candidate: &str) -> bool { |
| 832 | self.supports_catalog |
| 833 | } |
| 834 | |
| 835 | async fn create_message(&self, request: MessageRequest) -> anyhow::Result<MessageResponse> { |
| 836 | self.seen_models |
| 837 | .lock() |
| 838 | .expect("seen_models lock") |
| 839 | .push(request.model.clone()); |
| 840 | Ok(response( |
| 841 | r#"{"risk_level":"low","decision":"allow","reason":"ok"}"#, |
| 842 | Usage::default(), |
| 843 | )) |
| 844 | } |
| 845 | |
| 846 | async fn create_message_stream( |
| 847 | &self, |
| 848 | _request: MessageRequest, |
| 849 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 850 | unreachable!() |
| 851 | } |
| 852 | |
| 853 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 854 | Ok(true) |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | #[tokio::test] |
| 859 | async fn resolve_reviewer_model_honors_override_matches_catalog_and_falls_back_to_session() { |
| 860 | let custom = RouteStubClient::new("anthropic", "custom-claude", true); |
| 861 | assert_eq!( |
| 862 | resolve_reviewer_model(Some(" explicit-model "), &custom), |
| 863 | "explicit-model" |
| 864 | ); |
| 865 | assert_eq!(resolve_reviewer_model(None, &custom), "claude-sonnet-5-5"); |
| 866 | |
| 867 | let expected_catalog = [ |
| 868 | ("anthropic", "claude-sonnet-5-5"), |
| 869 | ("openai", "gpt-5.6"), |
| 870 | ("openai-codex", "gpt-6.1-sol"), |
| 871 | ("deepseek", "deepseek-v4-pro"), |
| 872 | ("deepseek-anthropic", "deepseek-v4-pro"), |
| 873 | ("google", "gemini-3.1-pro-preview"), |
| 874 | ("openrouter", "deepseek/deepseek-v4-pro"), |
| 875 | ("xai", "grok-4.7"), |
| 876 | ("zai", "GLM-5.3"), |
| 877 | ("moonshot", "kimi-k3.1-pro"), |
| 878 | ("minimax", "MiniMax-M3"), |
| 879 | ("minimax-anthropic", "MiniMax-M3"), |
| 880 | ]; |
| 881 | for (provider, expected) in expected_catalog { |
| 882 | let client = RouteStubClient::new(provider, "session-fallback", true); |
| 883 | assert_eq!( |
| 884 | resolve_reviewer_model(None, &client), |
| 885 | expected, |
| 886 | "provider={provider}" |
| 887 | ); |
| 888 | assert_eq!( |
| 889 | resolve_reviewer_model(Some(" "), &client), |
| 890 | expected, |
| 891 | "provider={provider}" |
| 892 | ); |
| 893 | |
| 894 | let unofficial = RouteStubClient::new(provider, "custom-route-model", false); |
| 895 | assert_eq!( |
| 896 | resolve_reviewer_model(None, &unofficial), |
| 897 | "custom-route-model", |
| 898 | "unofficial route must fall back to session model for {provider}" |
| 899 | ); |
| 900 | } |
| 901 | |
| 902 | let ollama = RouteStubClient::new("ollama", "qwen3-coder", true); |
| 903 | assert_eq!(resolve_reviewer_model(None, &ollama), "qwen3-coder"); |
| 904 | |
| 905 | let consulted = consult_reviewer_with_model( |
| 906 | &custom, |
| 907 | Some("chosen-reviewer"), |
| 908 | "{\"proposed_tool_call\":{}}", |
| 909 | &CancellationToken::new(), |
| 910 | ) |
| 911 | .await; |
| 912 | assert_eq!(consulted.reviewer_model, "chosen-reviewer"); |
| 913 | assert!(matches!(consulted.outcome, ReviewerOutcome::Allow { .. })); |
| 914 | assert_eq!( |
| 915 | custom.seen_models.lock().expect("seen_models").as_slice(), |
| 916 | &["chosen-reviewer"] |
| 917 | ); |
| 918 | } |
| 919 | } |
| 920 |