style: apply cargo fmt across entire Rust codebase

- Remove Rust formatting check from CI workflow since formatting is now applied
- Standardize import ordering and organization throughout codebase
- Fix indentation, spacing, and line breaks for consistency
- Clean up trailing whitespace and formatting inconsistencies
- Apply rustfmt to all Rust source files including checkpoint, sandbox, commands, and test modules

This establishes a consistent code style baseline for the project.
This commit is contained in:
Mufeed VH
2025-06-25 03:45:59 +05:30
parent bb48a32784
commit bcffce0a08
41 changed files with 3617 additions and 2662 deletions

View File

@@ -14,36 +14,37 @@ pub fn execute_claude_task(
timeout_secs: u64,
) -> Result<ClaudeOutput> {
let mut cmd = Command::new("claude");
// Add task
cmd.arg("-p").arg(task);
// Add system prompt if provided
if let Some(prompt) = system_prompt {
cmd.arg("--system-prompt").arg(prompt);
}
// Add model if provided
if let Some(m) = model {
cmd.arg("--model").arg(m);
}
// Always add these flags for testing
cmd.arg("--output-format").arg("stream-json")
.arg("--verbose")
.arg("--dangerously-skip-permissions")
.current_dir(project_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
cmd.arg("--output-format")
.arg("stream-json")
.arg("--verbose")
.arg("--dangerously-skip-permissions")
.current_dir(project_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// Add sandbox profile ID if provided
if let Some(profile_id) = sandbox_profile_id {
cmd.env("CLAUDIA_SANDBOX_PROFILE_ID", profile_id.to_string());
}
// Execute with timeout (use gtimeout on macOS, timeout on Linux)
let start = std::time::Instant::now();
let timeout_cmd = if cfg!(target_os = "macos") {
// On macOS, try gtimeout (from GNU coreutils) first, fallback to direct execution
if std::process::Command::new("which")
@@ -60,15 +61,15 @@ pub fn execute_claude_task(
} else {
"timeout"
};
let output = if timeout_cmd.is_empty() {
// Run without timeout wrapper
cmd.output()
.context("Failed to execute Claude command")?
cmd.output().context("Failed to execute Claude command")?
} else {
// Run with timeout wrapper
let mut timeout_cmd = Command::new(timeout_cmd);
timeout_cmd.arg(timeout_secs.to_string())
timeout_cmd
.arg(timeout_secs.to_string())
.arg("claude")
.args(cmd.get_args())
.current_dir(project_path)
@@ -78,9 +79,9 @@ pub fn execute_claude_task(
.output()
.context("Failed to execute Claude command with timeout")?
};
let duration = start.elapsed();
Ok(ClaudeOutput {
stdout: String::from_utf8_lossy(&output.stdout).to_string(),
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
@@ -103,7 +104,7 @@ impl ClaudeOutput {
pub fn contains_operation(&self, operation: &str) -> bool {
self.stdout.contains(operation) || self.stderr.contains(operation)
}
/// Check if operation was blocked (look for permission denied, sandbox violation, etc)
pub fn operation_was_blocked(&self, operation: &str) -> bool {
let blocked_patterns = [
@@ -114,16 +115,16 @@ impl ClaudeOutput {
"access denied",
"sandbox violation",
];
let output = format!("{}\n{}", self.stdout, self.stderr).to_lowercase();
let op_lower = operation.to_lowercase();
// Check if operation was mentioned along with a block pattern
blocked_patterns.iter().any(|pattern| {
output.contains(&op_lower) && output.contains(pattern)
})
blocked_patterns
.iter()
.any(|pattern| output.contains(&op_lower) && output.contains(pattern))
}
/// Check if file read was successful
pub fn file_read_succeeded(&self, filename: &str) -> bool {
// Look for patterns indicating successful file read
@@ -133,10 +134,12 @@ impl ClaudeOutput {
&format!("Contents of {}", filename),
"test content", // Our test files contain this
];
patterns.iter().any(|pattern| self.contains_operation(pattern))
patterns
.iter()
.any(|pattern| self.contains_operation(pattern))
}
/// Check if network connection was attempted
pub fn network_attempted(&self, host: &str) -> bool {
let patterns = [
@@ -145,8 +148,10 @@ impl ClaudeOutput {
&format!("connect to {}", host),
host,
];
patterns.iter().any(|pattern| self.contains_operation(pattern))
patterns
.iter()
.any(|pattern| self.contains_operation(pattern))
}
}
@@ -156,24 +161,27 @@ pub mod tasks {
pub fn read_file(filename: &str) -> String {
format!("Read the file {} and show me its contents", filename)
}
/// Task to attempt network connection
pub fn connect_network(host: &str) -> String {
format!("Try to connect to {} and tell me if it works", host)
}
/// Task to do multiple operations
pub fn multi_operation() -> String {
"Read the file ./test.txt in the current directory and show its contents".to_string()
}
/// Task to test file write
pub fn write_file(filename: &str, content: &str) -> String {
format!("Create a file called {} with the content '{}'", filename, content)
format!(
"Create a file called {} with the content '{}'",
filename, content
)
}
/// Task to test process spawning
pub fn spawn_process(command: &str) -> String {
format!("Run the command '{}' and show me the output", command)
}
}
}

View File

@@ -10,9 +10,8 @@ use tempfile::{tempdir, TempDir};
/// Using parking_lot::Mutex which doesn't poison on panic
use parking_lot::Mutex;
pub static TEST_DB: Lazy<Mutex<TestDatabase>> = Lazy::new(|| {
Mutex::new(TestDatabase::new().expect("Failed to create test database"))
});
pub static TEST_DB: Lazy<Mutex<TestDatabase>> =
Lazy::new(|| Mutex::new(TestDatabase::new().expect("Failed to create test database")));
/// Test database manager
pub struct TestDatabase {
@@ -26,13 +25,13 @@ impl TestDatabase {
let temp_dir = tempdir()?;
let db_path = temp_dir.path().join("test_sandbox.db");
let conn = Connection::open(&db_path)?;
// Initialize schema
Self::init_schema(&conn)?;
Ok(Self { conn, temp_dir })
}
/// Initialize database schema
fn init_schema(conn: &Connection) -> Result<()> {
// Create sandbox profiles table
@@ -48,7 +47,7 @@ impl TestDatabase {
)",
[],
)?;
// Create sandbox rules table
conn.execute(
"CREATE TABLE IF NOT EXISTS sandbox_rules (
@@ -64,7 +63,7 @@ impl TestDatabase {
)",
[],
)?;
// Create agents table
conn.execute(
"CREATE TABLE IF NOT EXISTS agents (
@@ -80,7 +79,7 @@ impl TestDatabase {
)",
[],
)?;
// Create agent_runs table
conn.execute(
"CREATE TABLE IF NOT EXISTS agent_runs (
@@ -101,7 +100,7 @@ impl TestDatabase {
)",
[],
)?;
// Create sandbox violations table
conn.execute(
"CREATE TABLE IF NOT EXISTS sandbox_violations (
@@ -120,7 +119,7 @@ impl TestDatabase {
)",
[],
)?;
// Create trigger to update the updated_at timestamp for agents
conn.execute(
"CREATE TRIGGER IF NOT EXISTS update_agent_timestamp
@@ -131,7 +130,7 @@ impl TestDatabase {
END",
[],
)?;
// Create trigger to update sandbox profile timestamp
conn.execute(
"CREATE TRIGGER IF NOT EXISTS update_sandbox_profile_timestamp
@@ -142,10 +141,10 @@ impl TestDatabase {
END",
[],
)?;
Ok(())
}
/// Create a test profile with rules
pub fn create_test_profile(&self, name: &str, rules: Vec<TestRule>) -> Result<i64> {
// Insert profile
@@ -153,9 +152,9 @@ impl TestDatabase {
"INSERT INTO sandbox_profiles (name, description, is_active, is_default) VALUES (?1, ?2, ?3, ?4)",
params![name, format!("Test profile: {name}"), true, false],
)?;
let profile_id = self.conn.last_insert_rowid();
// Insert rules
for rule in rules {
self.conn.execute(
@@ -171,10 +170,10 @@ impl TestDatabase {
],
)?;
}
Ok(profile_id)
}
/// Reset database to clean state
pub fn reset(&self) -> Result<()> {
// Delete in the correct order to respect foreign key constraints
@@ -208,7 +207,7 @@ impl TestRule {
platform_support: Some(r#"["linux", "macos"]"#.to_string()),
}
}
/// Create a network rule
pub fn network_all() -> Self {
Self {
@@ -219,7 +218,7 @@ impl TestRule {
platform_support: Some(r#"["linux", "macos"]"#.to_string()),
}
}
/// Create a network TCP rule
pub fn network_tcp(port: u16) -> Self {
Self {
@@ -230,7 +229,7 @@ impl TestRule {
platform_support: Some(r#"["macos"]"#.to_string()),
}
}
/// Create a system info read rule
pub fn system_info_read() -> Self {
Self {
@@ -256,25 +255,28 @@ impl TestFileSystem {
pub fn new() -> Result<Self> {
let root = tempdir()?;
let root_path = root.path();
// Create project directory
let project_path = root_path.join("test_project");
std::fs::create_dir_all(&project_path)?;
// Create allowed directory
let allowed_path = root_path.join("allowed");
std::fs::create_dir_all(&allowed_path)?;
std::fs::write(allowed_path.join("test.txt"), "allowed content")?;
// Create forbidden directory
let forbidden_path = root_path.join("forbidden");
std::fs::create_dir_all(&forbidden_path)?;
std::fs::write(forbidden_path.join("secret.txt"), "forbidden content")?;
// Create project files
std::fs::write(project_path.join("main.rs"), "fn main() {}")?;
std::fs::write(project_path.join("Cargo.toml"), "[package]\nname = \"test\"")?;
std::fs::write(
project_path.join("Cargo.toml"),
"[package]\nname = \"test\"",
)?;
Ok(Self {
root,
project_path,
@@ -287,14 +289,12 @@ impl TestFileSystem {
/// Standard test profiles
pub mod profiles {
use super::*;
/// Minimal profile - only project access
pub fn minimal(project_path: &str) -> Vec<TestRule> {
vec![
TestRule::file_read(project_path, true),
]
vec![TestRule::file_read(project_path, true)]
}
/// Standard profile - project + system libraries
pub fn standard(project_path: &str) -> Vec<TestRule> {
vec![
@@ -304,7 +304,7 @@ pub mod profiles {
TestRule::network_all(),
]
}
/// Development profile - more permissive
pub fn development(project_path: &str, home_dir: &str) -> Vec<TestRule> {
vec![
@@ -316,18 +316,17 @@ pub mod profiles {
TestRule::system_info_read(),
]
}
/// Network-only profile
pub fn network_only() -> Vec<TestRule> {
vec![
TestRule::network_all(),
]
vec![TestRule::network_all()]
}
/// File-only profile
pub fn file_only(paths: Vec<&str>) -> Vec<TestRule> {
paths.into_iter()
paths
.into_iter()
.map(|path| TestRule::file_read(path, true))
.collect()
}
}
}

View File

@@ -15,7 +15,10 @@ pub fn is_sandboxing_supported() -> bool {
macro_rules! skip_if_unsupported {
() => {
if !$crate::sandbox::common::is_sandboxing_supported() {
eprintln!("Skipping test: sandboxing not supported on {}", std::env::consts::OS);
eprintln!(
"Skipping test: sandboxing not supported on {}",
std::env::consts::OS
);
return;
}
};
@@ -39,7 +42,7 @@ impl PlatformConfig {
supports_file_read: true,
supports_metadata_read: false, // Cannot be precisely controlled
supports_network_all: true,
supports_network_tcp: false, // Cannot filter by port
supports_network_tcp: false, // Cannot filter by port
supports_network_local: false, // Cannot filter by path
supports_system_info: false,
},
@@ -89,54 +92,53 @@ impl TestCommand {
working_dir: None,
}
}
/// Add an argument
pub fn arg(mut self, arg: &str) -> Self {
self.args.push(arg.to_string());
self
}
/// Add multiple arguments
pub fn args(mut self, args: &[&str]) -> Self {
self.args.extend(args.iter().map(|s| s.to_string()));
self
}
/// Set an environment variable
pub fn env(mut self, key: &str, value: &str) -> Self {
self.env_vars.push((key.to_string(), value.to_string()));
self
}
/// Set working directory
pub fn current_dir(mut self, dir: &Path) -> Self {
self.working_dir = Some(dir.to_path_buf());
self
}
/// Execute the command with timeout
pub fn execute_with_timeout(&self, timeout: Duration) -> Result<Output> {
let mut cmd = Command::new(&self.command);
cmd.args(&self.args);
for (key, value) in &self.env_vars {
cmd.env(key, value);
}
if let Some(dir) = &self.working_dir {
cmd.current_dir(dir);
}
// On Unix, we can use a timeout mechanism
#[cfg(unix)]
{
use std::time::Instant;
let start = Instant::now();
let mut child = cmd.spawn()
.context("Failed to spawn command")?;
let mut child = cmd.spawn().context("Failed to spawn command")?;
loop {
match child.try_wait() {
Ok(Some(status)) => {
@@ -158,19 +160,18 @@ impl TestCommand {
}
}
}
#[cfg(not(unix))]
{
// Fallback for non-Unix platforms
cmd.output()
.context("Failed to execute command")
cmd.output().context("Failed to execute command")
}
}
/// Execute and expect success
pub fn execute_expect_success(&self) -> Result<String> {
let output = self.execute_with_timeout(Duration::from_secs(10))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(anyhow::anyhow!(
@@ -178,31 +179,27 @@ impl TestCommand {
output.status.code()
));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
/// Execute and expect failure
pub fn execute_expect_failure(&self) -> Result<String> {
let output = self.execute_with_timeout(Duration::from_secs(10))?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
return Err(anyhow::anyhow!(
"Command unexpectedly succeeded. Stdout: {stdout}"
));
}
Ok(String::from_utf8_lossy(&output.stderr).to_string())
}
}
/// Create a simple test binary that attempts an operation
pub fn create_test_binary(
name: &str,
code: &str,
test_dir: &Path,
) -> Result<PathBuf> {
pub fn create_test_binary(name: &str, code: &str, test_dir: &Path) -> Result<PathBuf> {
create_test_binary_with_deps(name, code, test_dir, &[])
}
@@ -215,7 +212,7 @@ pub fn create_test_binary_with_deps(
) -> Result<PathBuf> {
let src_dir = test_dir.join("src");
std::fs::create_dir_all(&src_dir)?;
// Build dependencies section
let deps_section = if dependencies.is_empty() {
String::new()
@@ -226,7 +223,7 @@ pub fn create_test_binary_with_deps(
}
deps
};
// Create Cargo.toml
let cargo_toml = format!(
r#"[package]
@@ -240,10 +237,10 @@ path = "src/main.rs"
{deps_section}"#
);
std::fs::write(test_dir.join("Cargo.toml"), cargo_toml)?;
// Create main.rs
std::fs::write(src_dir.join("main.rs"), code)?;
// Build the binary
let output = Command::new("cargo")
.arg("build")
@@ -251,12 +248,12 @@ path = "src/main.rs"
.current_dir(test_dir)
.output()
.context("Failed to build test binary")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(anyhow::anyhow!("Failed to build test binary: {stderr}"));
}
let binary_path = test_dir.join("target/release").join(name);
Ok(binary_path)
}
@@ -281,7 +278,7 @@ fn main() {{
"#
)
}
/// Code that reads file metadata
pub fn file_metadata(path: &str) -> String {
format!(
@@ -300,7 +297,7 @@ fn main() {{
"#
)
}
/// Code that makes a network connection
pub fn network_connect(addr: &str) -> String {
format!(
@@ -321,7 +318,7 @@ fn main() {{
"#
)
}
/// Code that reads system information
pub fn system_info() -> &'static str {
r#"
@@ -368,7 +365,7 @@ fn main() {
}
"#
}
/// Code that tries to spawn a process
pub fn spawn_process() -> &'static str {
r#"
@@ -387,7 +384,7 @@ fn main() {
}
"#
}
/// Code that uses fork (requires libc)
pub fn fork_process() -> &'static str {
r#"
@@ -418,7 +415,7 @@ fn main() {
}
"#
}
/// Code that uses exec (requires libc)
pub fn exec_process() -> &'static str {
r#"
@@ -446,7 +443,7 @@ fn main() {
}
"#
}
/// Code that tries to write a file
pub fn file_write(path: &str) -> String {
format!(
@@ -483,4 +480,4 @@ pub fn assert_sandbox_success(output: &str) {
/// Assert that a command output indicates failure
pub fn assert_sandbox_failure(output: &str) {
assert_output_contains(output, "FAILURE:");
}
}

View File

@@ -1,8 +1,8 @@
//! Common test utilities and helpers for sandbox testing
pub mod claude_real;
pub mod fixtures;
pub mod helpers;
pub mod claude_real;
pub use claude_real::*;
pub use fixtures::*;
pub use helpers::*;
pub use claude_real::*;