The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(agent): add failure policy class middleware tests
Steven Enamakel02a0983dd467
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rsnew file mode 100644index 0000000000..981b0ae977--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs@@ -0,0 +1,243 @@+//! Recovery classes for policy refusals and the read-only timeout floor.+//!+//! - A call the security policy blocked never ran, and its refusal tells the+//! model to try a narrower, permitted alternative. Production turns (Oct+//! 2026, ~18 breaker stops) ended after that first refusal because the+//! `policy` class had a budget of zero. A user's explicit denial and an+//! expired approval still stop at once.+//! - The timeout floor named tools that no longer exist (`web_search`); the+//! real names must keep their retryable timeouts from the side-effect+//! reading alone.++use super::super::call_effect::{call_effect, tool_sets_lookup, CallEffect};+use super::super::failure_policy::recovery_policy_with_effect;+use super::super::repeated_failure::recovery_policy;+use super::*;++/// The shape of a production refusal: the gate's marker, then its reason.+const SHELL_BLOCK: &str =+ "[policy-blocked] Unbounded system scan of '/' is not allowed; scope the command to the \+ project directory or a narrower path.";+const FETCH_BLOCK: &str = "[policy-blocked] Command not allowed by security policy: web_fetch";+const FILE_BLOCK: &str = "[policy-blocked] Security policy: forbidden path /etc/shadow";++async fn run_call(+ mw: &RepeatedToolFailureMiddleware,+ id: &str,+ tool: &str,+ args: serde_json::Value,+ outcome: Result<&str, &str>,+) {+ let mut call = TaToolCall::new(id, tool, args);+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();+ let mut result = match outcome {+ Ok(text) => TaToolResult::success(text),+ Err(error) => failing_result(tool, error),+ };+ mw.after_tool(&mut ctx(), &(), &invocation(id, tool), &mut result)+ .await+ .unwrap();+}++fn breaker() -> (+ RepeatedToolFailureMiddleware,+ SteeringHandle,+ crate::agent::tinyagents::HaltSummarySlot,+) {+ let handle = SteeringHandle::allow_all();+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());+ (mw, handle, slot)+}++// ── policy blocks get one alternative ───────────────────────────────────────++#[test]+fn a_policy_block_allows_one_alternative_but_a_user_denial_does_not() {+ for (tool, error) in [+ ("shell", SHELL_BLOCK),+ ("web_fetch", FETCH_BLOCK),+ ("file_read", FILE_BLOCK),+ ] {+ assert_eq!(+ recovery_policy(tool, error, false),+ Some(("blocked_by_policy", 1)),+ "{tool}"+ );+ }+ // The user said no, or never answered: asking again only re-prompts them.+ assert_eq!(+ recovery_policy("shell", "[policy-denied] The user declined this command", false),+ Some(("policy", 0))+ );+ assert_eq!(+ recovery_policy(+ "shell",+ "[policy-denied] Approval request timed out and expired",+ false+ ),+ Some(("policy", 0))+ );+}++#[tokio::test]+async fn a_blocked_shell_command_lets_the_model_try_a_narrower_one() {+ let (mw, handle, slot) = breaker();+ run_call(+ &mw,+ "scan-1",+ "shell",+ serde_json::json!({"command": "find / -name '*.log'"}),+ Err(SHELL_BLOCK),+ )+ .await;+ assert_eq!(drain_pause_count(&handle), 0, "one refusal is not a halt");+ assert!(slot.lock().unwrap().is_none());+ let nudges = drain_nudge_messages(&mw);+ assert_eq!(nudges.len(), 1, "{nudges:?}");+ assert!(nudges[0].contains("narrower"), "{nudges:?}");+ assert!(nudges[0].contains("Unbounded system scan"), "{nudges:?}");++ // The narrower alternative runs: the blocker is cleared, so a later+ // refusal starts a fresh budget.+ run_call(+ &mw,+ "scan-2",+ "shell",+ serde_json::json!({"command": "find ./logs -name '*.log'"}),+ Ok("logs/app.log"),+ )+ .await;+ run_call(+ &mw,+ "scan-3",+ "shell",+ serde_json::json!({"command": "du -sh /"}),+ Err(SHELL_BLOCK),+ )+ .await;+ assert_eq!(drain_pause_count(&handle), 0);+ assert!(slot.lock().unwrap().is_none());+}++#[tokio::test]+async fn a_second_consecutive_policy_block_stops_the_turn() {+ let (mw, handle, slot) = breaker();+ for (id, command) in [("scan-1", "find / -name x"), ("scan-2", "ls -R /")] {+ run_call(+ &mw,+ id,+ "shell",+ serde_json::json!({"command": command}),+ Err(SHELL_BLOCK),+ )+ .await;+ }+ assert_eq!(drain_pause_count(&handle), 1);+ let summary = slot.lock().unwrap().clone().unwrap();+ assert!(summary.contains("blocked_by_policy"), "{summary}");+}++#[tokio::test]+async fn blocks_on_different_tools_are_budgeted_separately() {+ let (mw, handle, slot) = breaker();+ run_call(+ &mw,+ "f-1",+ "web_fetch",+ serde_json::json!({"url": "https://blocked.test/a"}),+ Err(FETCH_BLOCK),+ )+ .await;+ run_call(+ &mw,+ "r-1",+ "file_read",+ serde_json::json!({"path": "/etc/shadow"}),+ Err(FILE_BLOCK),+ )+ .await;+ assert_eq!(drain_pause_count(&handle), 0);+ assert!(slot.lock().unwrap().is_none());+}++#[tokio::test]+async fn a_user_denial_still_stops_on_the_first_refusal() {+ let (mw, handle, slot) = breaker();+ run_call(+ &mw,+ "deny-1",+ "shell",+ serde_json::json!({"command": "rm -rf build"}),+ Err("[policy-denied] The user declined this command"),+ )+ .await;+ assert_eq!(drain_pause_count(&handle), 1);+ let summary = slot.lock().unwrap().clone().unwrap();+ assert!(summary.contains("`policy`"), "{summary}");+}++// ── the timeout floor, by production tool name ──────────────────────────────++fn search_spec(name: &str) -> tinysearch_bus::ToolSpec {+ tinysearch_bus::ToolSpec {+ name: name.to_string(),+ description: format!("{name} test spec"),+ parameters: serde_json::json!({"type": "object"}),+ }+}++/// The read tools as production registers them, so their own declarations+/// (permission level, policy, external effect) decide the timeout class.+fn production_read_tools() -> Vec<Box<dyn tinytools::Tool>> {+ use crate::security::SecurityPolicy;+ let security = std::sync::Arc::new(SecurityPolicy::default());+ let mut tools: Vec<Box<dyn tinytools::Tool>> = vec![+ Box::new(crate::tools::impl_network_web_fetch_for_tests(+ security.clone(),+ )),+ Box::new(tinytools_std::filesystem::FileReadTool::new(security.clone())),+ Box::new(tinytools_std::filesystem::ListFilesTool::new(security)),+ Box::new(crate::desktop::control::tools::DesktopTool::new(+ std::sync::Arc::new(crate::config::Config::default()),+ crate::desktop::control::tools::DesktopToolKind::Windows,+ )),+ ];+ for name in ["web_search_tool", "web_answer_tool", "web_contents_tool"] {+ tools.push(Box::new(crate::search::tools::TinySearchTool::recorded(+ search_spec(name),+ )));+ }+ tools+}++const PRODUCTION_READ_TOOLS: &[&str] = &[+ "web_fetch",+ "file_read",+ "list_files",+ "desktop_list_windows",+ "web_search_tool",+ "web_answer_tool",+ "web_contents_tool",+];++#[test]+fn production_read_tools_time_out_as_transient() {+ let lookup = tool_sets_lookup(vec![std::sync::Arc::new(production_read_tools())]);+ for name in PRODUCTION_READ_TOOLS {+ let args = serde_json::json!({"path": "src", "url": "https://example.com", "query": "q"});+ let effect = call_effect(Some(&lookup), name, &args);+ assert_eq!(effect, CallEffect::ReadOnly, "{name}");+ assert_eq!(+ recovery_policy_with_effect(name, "timed out", false, effect),+ Some(("transient", 2)),+ "{name}"+ );+ // Without the registry (name only), the same answer.+ assert_eq!(+ recovery_policy(name, "timed out", false),+ Some(("transient", 2)),+ "{name} by name"+ );+ }+}